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.
The synchronized list returned by
Collectionswon’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 asynchronizedblock. The Javadoc states: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
synchronizedblock to youraddmethod and use the same lock that you’ll use when iterating over it.