views:

66

answers:

5

Hi,

I have two threads and one 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

A: 

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

btreat
Do you mean methods of the "local object" or the methods of the class?
A: 

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.

jdehaan
+1  A: 

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()...
}
Greg Harman
sounds logical to mee! I'll try!
If a method reads from the list and then modifies it based on what it read, you need one block around both methods.
Kathy Van Stone
Do I need to put synchronized even if I red the data... to ensure that no modification is done while I finish with reading?
Well, that depends on your needs. As @Kathy suggests, you can ensure that while you work with a value it hasn't been overwritten in the array. If you don't care about that, then you don't need any of this.
Greg Harman
@chronosphenomena You need to put synchronized even if you read the data to both ensure that you don't see a partial state and to ensure that changes made are visible to the reading thread.
Kathy Van Stone
@Kathy - yes, you're right. I just went back and doublechecked - ArrayLists are not thread-safe. Along that line of thinking, another approach might be to replace the ArrayList with a Vector, which is thread-safe.
Greg Harman
@Greg Harman The current recommended practice is to use the synchronized list wrapper (in java.util.Collections) or one of the java.util.concurrent classes over Vector.
Kathy Van Stone
A: 

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

Xorty
A: 

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

Kathy Van Stone