14.07. Static synchronization

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 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 a 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

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments