Good to know

Here are some common cases that imply synchronizations:

  • Two threads can execute concurrently a synchronized static method and a non-static method of the same class (see the OllAndCll class of the P200_ObjectVsClassLevelLocking app). This works because the threads acquire locks on different objects.
  • Two threads cannot concurrently execute two different synchronized static methods (or the same synchronized static method) of the same class (check the TwoCll class of the  P200_ObjectVsClassLevelLocking application). This does not work because the first thread acquires a class-level lock. The following combinations will output, staticMethod1(): Thread-0therefore, only one static synchronized method is executed by only one thread:
TwoCll instance1 = new TwoCll();
TwoCll instance2 = new TwoCll();
  • Two threads, two instances:
new Thread(() -> {
instance1.staticMethod1();
}).start();

new Thread(() -> {
instance2.staticMethod2();
}).start();
  • Two threads, one instance:
new Thread(() -> {
instance1.staticMethod1();
}).start();

new Thread(() -> {
instance1.staticMethod2();
}).start();
  • Two threads can concurrently execute non-synchronized, synchronized static, and synchronized non-static methods (check the OllCllAndNoLock class of the P200_ObjectVsClassLevelLocking application).
  • It is safe to call a synchronized method from another synchronized method of the same class that requires the same lockThis works because synchronized is re-entrant (as long as it is the same lock, the lock acquired for the first method is used in the second method as well). Check the TwoSyncs class of the P200_ObjectVsClassLevelLocking application.
As a rule of thumb, the synchronized keyword can be used only with static/non-static methods (not constructors)/code blocks. Avoid synchronizing non-final fields and String literals (instances of String created via new are OK).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset