Reputation: 1249
Suppose i have a code snippet where i want to insert a node in a Linked List and for consistency i used following coding mechanism : Assume that current and next are elements of LinkedList where current represent the Object we are working on and next represent the next object of List.
synchronized(current) {
synchronized(next) {
.............
}
}
and i performed an insertafter for current Object. Can the same functionality be achieved through synchronized methods. Since we can obtain lock only on a single object. So synchronized insertAfter wont prevent someone to use insertBefore.
Upvotes: 0
Views: 75
Reputation: 14974
A synchronized method is nothing but syntactic sugar for synchronized(this) {...}
.
So the literal answer to your question is "not easily". You would need two different objects where the two synchronized methods are declared, and call one from the other. But it seems like a bad idea.
In general, I question the goal of trying to reduce an explicit synchronized block to a synchronized method. Synchronized blocks are more readable, and let you encapsulate the lock object to prevent undesired lock contention if some other code decides to use the same instance as the lock for some reason.
Also, are you sure you need the kind of fine-grained locking you're trying to do? This seems error-prone... a more straightforward code would synchronize on the same object for any operation on the list.
Upvotes: 1
Reputation: 65889
This pattern is well know to result in what is called deadly embrace
. Imagine someone else making use of your code and also doing the equivalent of an insertBefore
:
synchronized(next) {
synchronized(current) {
.............
}
}
This would obviously end in tears.
The obvious answer is not to synchronize on the nodes but on the joins between the nodes.
Upvotes: 1