In my code, I use a synchronized block on the resource set inside another synchronized block on the same resource. This did not cause me any problems so far, but I’m curious: what are the consequences if any? Will these synchronized blocks conflict with each other?
Set<myClass> set = Collections.synchronizedSet(new HashSet<myClass>());
synchronized(set) {
set.add(new myClass());
...
writeSetContentsToFile();
}
public synchronized void writeSetContentsToFile() {
synchronized(set) {
...
}
}
The set is accessed and changed continously by other threads. I synchronized writeSetContentsToFile(), so there won’t be any conflicts at the file resource, and again, there is a synchronized block inside writeSetContentsToFile(), to make sure no changes are made to the set while iterating over it.
In some ways you answered your own question, it works but its confusing. Its best to simplify the code if you can. You would need to look at the rest of the code to determine whether this is possible.