Static synchronization

  • Eclipse: Oxygen
  • Java: 1.8

The concept of static synchronization is shown here. For the issue regarding the inconsistency caused due to the multiple objects accessing the synchronized block causes an error, hence by declaring the function as static, we can avoid the same. Therefore, we can directly access the methods by the class name.

As you can see, we have a class Brackets. Inside the class, there is a generate() method. We want one thread to finish printing the message within the method then only another thread should start executing the method.

Here we have created two objects bracket1 and bracket2. These two objects are calling the generate() method.

Here we have used a non-static synchronized method. Generally, this method holds the lock on the current object and it can run at the same time. It can produce inconsistency.

The following program demonstrates the output without using static synchronization.

Output

[[[[[]]][[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

Sometimes making use of the single object is not possible. Then we should go for static synchronization.

Whenever we make use of static elements as synchronized, the lock would be based on the class directly.

The following program demonstrates the synchronization using the static synchronized method.

Output

[[[[[]]]]]Generated by thread: Thread 2

[[[[[]]]]]Generated by thread: Thread 2

[[[[[]]]]]Generated by thread: Thread 2

[[[[[]]]]]Generated by thread: Thread 2

[[[[[]]]]]Generated by thread: Thread 2

[[[[[]]]]]Generated by thread: Thread 1

[[[[[]]]]]Generated by thread: Thread 1

[[[[[]]]]]Generated by thread: Thread 1

[[[[[]]]]]Generated by thread: Thread 1

[[[[[]]]]]Generated by thread: Thread 1

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu