If I have something like below, so what does that mean inside synchronized block
synchronised (syncObject) {
Basically, it will means only one thread can be inside the above block and as soon as one thread is finished executing, second thread will enter that synchronized block synchronised (syncObject). Right?
Can anyone explain to me in a LayMan language so that I can get better picture?
private static final class Task implements Runnable {
{
private static Object syncObject = new Object();
public Task(Command command, BlockingQueue<Integer> pool1, BlockingQueue<Integer> pool2) {
this.command = command;
this.existPool = pool1;
this.newPool = pool2;
}
public void run()
{
synchronised (syncObject) {
if() {
existId = existPool.take();
attributeMethod(existId);
} else if() {
newId = newPool.take();
attributeMethod(newId);
}
}
}
}
// So I need to make this method synchronized or not? Currently I have made this synchronized
private synchronized void attributeMethod(int range) {
// And suppose If I am calling any other method here-
sampleMethod();
}
// What about this method, I need to make this synchronized as well? or not?
private synchronized void sampleMethod() {
}
Right!
No you don’t. Assuming that the method is only going to be called from within the synchronized block in the
run()method, that block will already prevent multiple threads from executing the method simultaneously. So declaring the method to besynchronizedis redundant.However, I should point out some things:
When you declare an instance method as
synchronized, it will synchronize onthis; i.e. on theTaskobject. But yoursynchronizedblock is synchronizing on a different object … the object insyncObject. In this case, this doesn’t matter. However, if thesynchronizedblock in therun()method wasn’t there, you would find that the threads were attempting synchronizing on different objects … and you would NOT get mutual exclusion.By synchronizing at the top level of the
run()method … using a single sharedsyncObjectfor all threads that execute that task … you are effectively making the tasks run one at a time. This completely negates any benefits of using threads.It is good practice to declare the variable containing a private lock object (such as
syncObject) to befinal. This avoids the possibility that something might overwrite it … resulting in a synchronization failure.