Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35597

Shouldn't Java compiler force to make synchronize?

Consider the following scenario.

public synchronized String getData(){
    return getInfo();
}
private String getInfo(){                   
    // operation here should synchronized
    return  "Synchronize Info";
}

If some one by pass the flow of this operation. System may become unstable, if Java compiler force to make getInfo synchronized that kind of issues won't be there. But Java compiler doesn't force to do so. Now developer should responsible for make getInfo synchronized or not. Why Java doesn't force to make getInfo synchronized ?

Upvotes: 0

Views: 90

Answers (2)

Boann
Boann

Reputation: 50061

It's impossible for the Java compiler to enforce this usefully. You could invent a rule that synchronized methods can only call methods of the same object if they are synchronized, but it's not helpful except in quite narrow scenarios. If getInfo() were public, getData() could easily call a different class, which calls back to getInfo() on the original object.

Also, synchronization can be used on individual statements rather than whole methods, and there are other locks too. Trying to design compiler rules to prevent synchronized code using unsynchronized data for all these cases would be complicated or impossible.

Actually, it's legitimate to want to call a method without the cost of synchronization at times when it's known that only thread is using the object. Deciding which parts of the object should be locked, and when, is a complicated design problem only the human programmer can do.

So Java can't/won't prevent you from writing code which is not theadsafe. It doesn't care. If by "system" you mean "computer", it will not "become unstable". At worst, that one class will be buggy.

Upvotes: 2

mattdee123
mattdee123

Reputation: 213

From the Java documentation at http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html, "it is not possible for two invocations of synchronized methods on the same object to interleave".

In other words, if you call getData, then any future calls to getData on the same object will wait until that one is done. So even when the control flow moves into getInfo, the system will still block any future calls to getData until the first returns, so there is no reason why getInfo should be blocked. I hope that helps!

Upvotes: 1

Related Questions