I have a Collections.synchronizedList of WeakReference, _components;
I wrote something like the following, expecting the complier to complain:
public boolean addComponent2(Component e) { synchronized (_components) { return _components.add(new WeakReference<Component>(e)); } }
But the compiler is perfectly satisfied. Note that List.add() returns TRUE. So ok, any exit from a synchronized block releases the lock, but doesn't this LOOK strange? It's kind of like a "hole" in the block, similar to using return in a loop.
Would you be happy maintaining code like this?
Some of the given reasons are: some evil code may steal your lock (very popular this one, also has an "accidentally" variant) all synchronized methods within the same class use the exact same lock, which reduces throughput. you are (unnecessarily) exposing too much information.
In simple two lines Disadvantage of synchronized methods in Java : Increase the waiting time of the thread. Create performance problem.
To acquire a lock on an object for a specific set of code block, synchronized blocks are the best fit. As a block is sufficient, using a synchronized method will be a waste. More specifically with Synchronized Block , it is possible to define the object reference on which are want to acquire a lock.
From this we can conclude that synchronizing on the smallest possible code block required is the most efficient way to do it. However the practical difference between synchronizing a method vs. a code block really depends on the method and what code is being left out of the synchronized block.
It's absolutely fine - as is returning from a loop, or from a try
block which has an appropriate finally
block. You just need to be aware of the semantics, at which point it makes perfect sense.
It's certainly simpler code than introducing a local variable for the sake of it:
// Ick - method body is now more complicated, with no benefit public boolean addComponent2(Component e) { boolean ret; synchronized (_components) { ret = _components.add(new WeakReference<Component>(e)); } return ret; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With