Synchronize an object when possible

Is it possible to synchronize a block whenever it detects that the object is not null to lock. His best effort is trying to synchronize. I can write the code this way, but it looks a bit detailed:

if ( lock_object != null ) { synchronized(lock_object) { doSomething(); } } else { doSomething(); } 

Is there a better way to structure this code? Tks!

+4
source share
2 answers

Perhaps, but it makes no sense. The doSomething method reads / writes some data, say, the fields of the object to which the method belongs. The most obvious and reliable way is to declare the doSomething synchronized method, as well as all other methods that can be called from different threads. The synchronized block is used only for optimization, and novice programmers should avoid using it.

As for the β€œbest effort,” the best programming effort means no less reliable and proven functionality. All other "efforts" are not the best, including your code.

+1
source

as you said:

synchronizes a block whenever it detects an object is not null

I think you better use for now:

 while( lock_object != null ){ synchronized(lock_object) { // your not null activities } } // your null activities 
0
source

Source: https://habr.com/ru/post/1494001/


All Articles