The synchronized Statement Java Help

The synchronized Statement 
While creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases. To understand why, consider the following. Imagine that you want to synchronize access to objects of a class that was not ~signed for multithreaded access. That is, the class. does not use 'synchronized tenth qs. Further, this class was not created by you, but by a third party, and you do not have access to the source code you can't add synchronized to the appropriate methods within the class. How can access to an object of.this class be synchronized? Fortunately, the solution to this problem is quite easy: You simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized statement:

synchronized (object) I

II statements to be synchronized

Here, object is a reference to the object being synchronized. If you want to synchronize only a single statement, then the curly braces arc nut needed. A synchronized block ensures that a call to a method that is n member of object occurs only after the current thread has successfully entered object's monitor., Here is an alternative version of the preceding example, using a synchronized block within the runt ) method:

Here, the call( ) method is not modified by synchronized. Instead, the synchronized .statement is used inside Caller's run() method. This causes the same correct output as the preceding example, because each thread waits for the prior one to finish before proceeding.

Posted on September 17, 2014 in The Complete Reference

Share the Story

About the Author

Back to Top
Share This