updating mutable list in multithreading

Im new to multiThreading. I have a list which is referenced by all thread. On certain condition, i want the list to be updated with values from database. The update could happen in any of those thread. How to make certain that when the list is updated, all thread which is looping through all item in list will receive an update to the list they reading through?

Answer

One of the most common situations in concurrent programming occurs when more than one execution thread shares a resource. In a concurrent application, it is normal that multiple threads read or write the same data or have access to the same file or database connection. These shared resources can provoke error situations or data inconsistency and we have to implement mechanisms to avoid these errors. The solution for these problems comes with the concept of critical section. A critical section is a block of code that accesses a shared resource and can’t be executed by more than one thread at the same time. To implement critical sections, Java (and almost all programming languages) offers synchronization mechanisms

synchronization mechanisms offered by the Java language:

The keyword synchronized

The Lock interface and its implementations

Make the method synchronized where you are writing to the list,so that only one thread can update the list.

synchronized void updateList(){
   //your code here
}

Leave a Reply

Your email address will not be published. Required fields are marked *