Just talk about 3 Java interview questions—— 02

4. How to handle concurrent modifications to Collection in Java?

Concurrent modifications to collections in Java can lead to a range of problems, such as unexpected behavior, indeterminate results, and even throwing ConcurrentModificationException. To handle concurrent modifications of collections in Java, you can use one of the following methods:

  • Using synchronized collections: One way to handle concurrent modifications to a collection is to use synchronized collections. A synchronized collection is a thread-safe collection that ensures that only one thread can modify the collection at a time. We can create a synchronized collection by calling the Collections.synchronizedCollection() method and passing in the collection to be synchronized. For example:
List<String> list = new ArrayList<>();  
List<String> synchronizedList = Collections.synchronizedList(list);
  • Using concurrent collections: Another way to handle concurrent modifications to a collection is to use concurrent collections. Concurrent collections are thread-safe collections that allow multiple threads to modify the collection simultaneously without the need for external synchronization. The (java.util.concurrent) package provides a series of concurrent collection classes, such as ConcurrentHashMap, ConcurrentLinkedDeque, and ConcurrentSkipListSet.

  • Using explicit locking: We can also use explicit locking to handle concurrent modifications to the collection. We can use the synchronized keyword or (java.util.concurrent.locks) package to lock the collection when modifying the collection. For example:

List<String> list = new ArrayList<>();
synchronized(list) {
    
    
    list.add(“foo”);
}
  • Proper use of iterators: When iterating over a collection, you should use the Iterator interface to avoid concurrent modifications. If you modify the collection while iterating it using an iterator, you will receive a ConcurrentModificationException. Instead, you can use the iterator's remove() method to remove elements from a collection while iterating over it. For example:
List<String> list = new ArrayList<>();  
Iterator<String> iterator = list.iterator();  
while (iterator.hasNext()) {
    
      
    String element = iterator.next();  
    if (someCondition) {
    
      
        iterator.remove();
    }  
}

5. How to implement deadlock situation in Java?

A deadlock in Java is when two or more threads are blocked forever, waiting for each other to release the lock or resource they hold. Implementing a deadlock situation in Java involves creating a scenario where two or more threads are blocked, waiting for each other, and unable to proceed further. Here is an example of how to create a deadlock in Java:

image.png

public class Main {
    
      

    private static final Object lock1 = new Object();  
    private static final Object lock2 = new Object();  

    public static void main(String[] args) {
    
      
  
        Thread thread1 = new Thread(() -> {
    
      

            synchronized (lock1) {
    
      
                System.out.println(Thread 1 acquired lock 1);  
                try {
    
      
                    Thread.sleep(100);  
                } catch (InterruptedException e) {
    
      
                    e.printStackTrace();  
                }
             
                synchronized (lock2) {
    
      
                    System.out.println(Thread 1 acquired lock 2);  
                }  
            }  
        });  
  

        Thread thread2 = new Thread(() -> {
    
      

            synchronized (lock2) {
    
      
                System.out.println(Thread 2 acquired lock 2);  
                try {
    
      
                    Thread.sleep(100);  
                } catch (InterruptedException e) {
    
      
                    e.printStackTrace();  
                }  

                synchronized (lock1) {
    
      
                    System.out.println(Thread 2 acquired lock 1);  
                }  
            }  
        });  

        thread1.start();  
        thread2.start();  
    }  
}

In this example, we have two threads, thread1 and thread2, each trying to acquire two locks: lock1 and lock2.

  • Thread 1 first acquires lock 1, then waits 100 milliseconds before trying to acquire lock 2.
  • At the same time, thread2 acquires lock2 and waits 100 milliseconds before trying to acquire lock1.

Because both threads are waiting for the other to release the locks they hold, a deadlock situation occurs and the program is stuck forever, unable to continue.

6. Can you explain the difference between "Reader-Writer" lock and "ReentrantReadWriteLock" in Java? Which one is more flexible to use?

Read-write lock:

Read-write locks allow multiple threads to read from a shared resource simultaneously, but only one thread can write at a time. When a thread wants to write to a resource, it must wait for all readers to finish reading before it can acquire the lock.

Read-write locks are non-reentrant, which means that the thread holding the read lock cannot acquire the write lock without releasing the read lock. Similarly, a thread holding a write lock cannot acquire a read lock without releasing the write lock.

Reentrant read-write lock:

ReentrantReadWriteLock is a more flexible implementation of read-write locks. It allows multiple threads to acquire read locks at the same time, and also allows a thread holding a read lock to acquire a write lock without first releasing the read lock. This allows a thread to upgrade a read lock to a write lock.

Additionally, ReentrantReadWriteLock is reentrant, which means that the thread holding the lock for reading or writing can acquire the lock again without releasing the lock first.

Overall, a reentrant read-write lock provides more flexibility than a read-write lock, but it is also more complex and can lead to deadlocks if used incorrectly. ReentrantReadWriteLock is generally recommended when finer-grained control of locks is required, and Reader-Writer locks are recommended when simplicity is required.

Guess you like

Origin blog.csdn.net/qq_41340258/article/details/133100766