Reputation: 1591
Is it possible to synchronized a block whenever it detects an object is not null for locking. Its some sort of best effort attempt to synchronized. I can write the code this way but seems a bit verbose:
if ( lock_object != null )
{
synchronized(lock_object) {
doSomething();
}
}
else
{
doSomething();
}
Is there a better way of structuring this code?
Upvotes: 4
Views: 118
Reputation: 13535
It is possible, but has no sense. The method doSomething
reads/writes some data, say, fields of the object the method belongs to. The most evident and reliable way is to declare the method doSomething
synchronized, as well as all other methods which can be called from different threads. Synchronized block is used only for optimizations, and novice programmers should avoid using it.
As for the "best effort", best effort in programming means no less than reliable and proven functionality. All other "efforts" are not best, including your code.
Upvotes: 1
Reputation: 604
as you said :
synchronized a block whenever it detects an object is not null
I think you'd better use while as :
while( lock_object != null ){
synchronized(lock_object) {
// your not null activities
}
}
// your null activities
Upvotes: 0