开发者

Java synchronization problem

I have two threads and one开发者_JAVA百科 class.

Thread1 updates the local object of the class via 3 different methods. The local object (behind the scene) uses some sort of ArrayList to store data. Three methods (mentioned earlier), are doing something with elements of the list...

Thread2 queries the local object (content of array list).

PROBLEM: How can I make sure that none of the three updating methods (Thread1) will modify the content of the "local object" while it's being read by Thread2?

Thanks


Put a common lock around portions of the code that modify the ArrayList using synchronized. It doesn't really matter what object you use as a lock, as long as it's the same, but I think using the ArrayList itself would be idiomatic:

synchronized (list) {
   list.put()...
}

synchronized (list) {
   list.get()...
}


You can make the methods which access the data (read or write) 'synchronized'.


In all methods mentionned above use a synchronized(your_list) { ... code ... } context, making the methods synchronized is a maybe to hard solution, blocks more than needed if you just want to protect the list and not the whole object.


Using synchronized keyword. You are dealing with problem known as critical sections


I suggest you read the Java Tutorial on Concurrency, in particular the section on synchronization. You have a straightforward case of synchronization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜