Java synchronized – 4 types – 2 ways for the same purpose

Tram Ho

The purpose here is for the value of the variable to be synchronized between threads. Two ways to do it here are how to use the monitor mechanism by putting the synchronized keyword outside the method or inside the method.

  • A method that needs to be synchroized needs to have a watch/monitor mechanism (to turn the value by how much it needs to sync) before it executes.
  • For a class method (the method has the static keyword preceded by the keyword), the observer attaches to the Class object for the classes of the method used.
  • For instance methods (methods need the new keyword to instantiate the class, methods belong to that class), the observer/watcher using the this keyword (the object on which the method is invoked) is used.

All of the examples below are of all four types: static and non-static variables, and static and non-static methods.

Method 1:

Way 2

image.png

2 ways are the same for the same purpose. If synchronized is not declared outside the variable/method, it must be declared inside. In some cases, use the this keyword, in other cases use Java reflection synchronized (Class.forName("BumpTest")) . For the same purpose of keeping 2 values ​​synchronized with each other in a Multi-thread environment, concurrent, there are 2 different ways to do it, both with instance variable, instance method, class variable (variable with static preceded) , class method (method preceded by static).

Reference documentation: Java Language Specification – language level 19:https://docs.oracle.com/javase/specs/jls/se19/html/jls-8.html#jls-8.4.3.6

Source code https://gist.github.com/donhuvy/94dc3edd94890b87721f1530b115976b#file-test-java-L5

Share the news now

Source : Viblo