Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - general synchronizedList question

I have a general question regarding synchronized List.
Lets say that in the constructor I am createing a list

List synchronizedList = Collections.synchronizedList(list);

and I have one method adds an object to the list.

public void add(String s){ 
    synchronizedList.add(s)
}

There is another thread that checks every few seconds if there are a few rows , dump it to a file and deletes them all.

Now lets say I iterate each row and save it to the db. after all iteration I clear the list.

How does the multithread support help me?
I could add an element to the list just before the clear() in the other thread occurs .
Unless I manage the lock myself (which I dont realy need a synched list for that ) it myself.

like image 1000
Bick Avatar asked May 24 '11 07:05

Bick


2 Answers

The synchronized list returned by Collections won't help in your case. It's only good if you need to guarantee serial access to individual method calls. If you need to synchronize around a larger set of operations, then you need to manually wrap that code in a synchronized block. The Javadoc states:

It is imperative that the user manually synchronize on the returned list when iterating over it.

If your list is used elsewhere you can at least safeguard it from individual method calls that would otherwise not be thread-safe. If you're entirely managing the list however, you can just add a synchronized block to your add method and use the same lock that you'll use when iterating over it.

like image 173
WhiteFang34 Avatar answered Oct 02 '22 01:10

WhiteFang34


synchronizedList indeed only guarantees that every method call on the list is synchronized. If you need multiple operations to be done in a synchronized way, you have to handle the synchronization yourself.

BTW, this is explicitely said in the javadoc for Collections.synchronizedList :

It is imperative that the user manually synchronize on the returned list when iterating over it:

  List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized(list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }
like image 27
JB Nizet Avatar answered Oct 02 '22 02:10

JB Nizet