i

JAVA Complete Course

Synchronization: Methods And Statements

In multi-threaded applications the situation where multiple threads try to access the same resources happens very often and it finally produces erroneous and unforeseen results. So we need to be sure that only one thread will access any resource at a given time. We can use for this some synchronization mechanism.

Java provides us the mechanism to synchronize method or the block inside the method. A synchronized block in Java can be done on some object. If we have few synchronized blocks on the same object we will have one thread executing inside them at a time.

Below is an example, where we synchronize the Sender object inside the run() method of the ThreadedSend class. Alternately to it, we can make the whole send() block as synchronized and it will produce the same result. In that case, we  don’t have to synchronize the Message object inside the run() method in ThreadedSend class.

Let’s see the same example on the synchronized method:

One note is that we don’t need to synchronize whole method in some cases, so in this case synchronizing only small block of method will be preferable.