I have a thread safe class Container:
public class Container {
private int x;
...
public synchronized int getX();
public synchronized void setX(int x);
}
Then I have a list of containers:
List<Container> containers;
I would like to iterate through the list, aquire the container's lock at each iteration and, only at the end of loop, release all locks. Something like this:
for(Container c : containers) {
c.lock();
//do stuff
}
for(Container c : containers)
c.unlock();
I still want other threads to be able to continue to use getX and setX methods of unlocked containers, but for various reasons I do not want to allow that for already analysed containers.
Do you know the java code for that?
Better ideas are also appreciated.
lock()
andunlock()
first and last ingetX
andsetX
?