在同步块中使用Vector会有什么不同吗?

Vin*_*C M 4 java synchronization vector

我在接受采访时被问到这个问题.

矢量已经同步.在同步块中调用它会有什么不同吗?

       synchronized{
            // Call the vector here
       }
Run Code Online (Sandbox Code Playgroud)

我的答案是,除了性能损失之外,没有任何区别.

答案是否正确?

Vin*_*lds 12

不,这不完全正确.VectorVector实例本身上同步,而synchronized块实际上在保存的实例上同步Vector.进入同步块的两种方法必须首先获取与之关联的监视器this,然后获取与该Vector实例关联的监视器.

边缘情况是,如果其中一个线程持有另一个需要的监视器(如果你还有其他同步块),那么你可能会遇到死锁.

然而,仅考虑发布的代码部分,首先获取监视器的线程this将首先在Vector上执行操作.此外,Vector实例上的操作序列可以由第一线程执行,而不需要第二线程的任何操作交错; 如果要在Vector实例上执行原子操作序列,则必须执行此操作,而在普通同步Vector实例上则不是这种情况.为了在伪代码中表示这一点,如果在执行相同块的两个或多个线程之间发生上下文切换,则下面表示的两种情况中的操作序列将是不同的:

案例A.

synchronized
{
    vector.add(a);
    vector.add(b);
/*
 * a and b are always added to the vector in sequence.
 * If two threads execute this block, the vector will contain {a,b,a,b}.
 */
}
Run Code Online (Sandbox Code Playgroud)

案例B

{
    vector.add(a);
    vector.add(b);

 /*
  * a and b need not be added to the vector in sequence.
  * If two threads execute this block, the vector will contain one of {a,b,a,b}, {a,a,b,b}....
  */
}
Run Code Online (Sandbox Code Playgroud)