I am recently using Java Threads and I am trying to implement a method able to restricts a block of code to be execute only by one thread, lets called “single”.
One naive solution that I already implemented is as follows:
if(readFlag())
{
synchronized(this)
{
flag = false;
// do some work
}
}
Where :
public Boolean synchronized readFlag() {return flag;}
This naive solution works fine for only one “single” block, but the problem occurs when I try to use multiple “single” code blocks. Since I can not use the same flag, because different threads may whan to enter different “single” code blocks at the same time.
Another solution could be the use of an array of flags variables one for each “single” but this solution would have problems (or require the use of barriers) when executing “single” code blocks inside loops, beside not being very flexible.
My question is:
How could I improve this solution to allow the execution of various “single” code blocks and to allow the execution of the same single code block multiple times (e.g. a single code block inside a loop).
You can change the object you synchronize on. There is no need to synchronize on
this, unless you need to. If you have two blocks that need to be synchronized but that can both be executed at the same time (each by one thread only), you can do something likeAlso take a look at the ReentrantReadWriteLock for more sophisticated locking (to allow multiple readers but only one writer).