0

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.

4

2 回答 2

1

同步方法只不过是synchronized(this) {...}.

所以你的问题的字面答案是“不容易”。您将需要两个不同的对象,其中声明了两个同步方法,并从另一个对象中调用一个。但这似乎是个坏主意。

一般来说,我质疑试图将显式同步块减少为同步方法的目标。同步块更具可读性,并且允许您封装锁对象以防止在其他代码出于某种原因决定使用与锁相同的实例时发生不希望的锁争用。

另外,你确定你需要你想要做的那种细粒度的锁定吗?这似乎容易出错......更直接的代码将在同一个对象上同步列表上的任何操作。

于 2013-10-07T23:47:50.253 回答
1

众所周知,这种模式会导致所谓的deadly embrace. 想象一下其他人在使用您的代码并执行相当于insertBefore

synchronized(next) {
     synchronized(current) {
              .............
     }
}

这显然会以眼泪收场。

显而易见的答案不是在节点上同步,而是在节点之间的连接上同步。

于 2013-10-07T23:44:21.710 回答