从方法返回的同步代码中的对象

Object in Synchronized code returned from a method

我想要一个同步块,其中要同步的对象是从方法调用return编辑的:

...
synchronized( someGetMethod() ) {
// synchronized block
}
...

是否假设 "someGetMethod" 是同步的或只有“// 同步块”部分?

提前致谢

编辑: 我有一个集合(要锁定的对象映射)。 "someGetMethod" 检查地图上是否存在对象,如果不存在,它将添加它并 return 它以便被锁定。 从下面的答案中,我了解到 "someGetMethod" 可以 return 一个已经在 Map 上的值,但是在进入同步块之前,切换到另一个线程,这可能会删除上面的值。结果,另一个线程可能通过 "someGetMethod" 进行相同的检查,现在得到不同的结果。所以我似乎应该从同步块中删除,有更好的选择吗?

编辑2: 感谢大家的帮助。 我发现了一个类似的问题 - Java synchronized block using method call to get synch object

这个:

synchronized( someGetMethod() ) {
// synchronized block
}

相同
Object obj = someGetMethod();
synchronized( obj ) {
// synchronized block
}

所以不,someGetMethod() 没有以同步方式调用。

如果你想让它同步,要么声明方法同步,要么显式同步,例如:

synchronized (this) {
  synchronized( someGetMethod() ) {
    // synchronized block
  }
}

someGetMethod() 是在与表达式结果关联的监视器被线程锁定之前计算的表达式。

14.19. The synchronized Statement

A synchronized statement is executed by first evaluating the Expression. Then:

  • If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason.

  • Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

  • Otherwise, let the non-null value of the Expression be V. The executing thread locks the monitor associated with V. Then the Block is executed, and then there is a choice:

    • If execution of the Block completes normally, then the monitor is unlocked and the synchronized statement completes normally.

    • If execution of the Block completes abruptly for any reason, then the monitor is unlocked and the synchronized statement completes abruptly for the same reason.

您不能进入同步块,计算表达式,然后查看与结果关联的监视器。 你是如何进入这个块而不首先计算它的表达式的? 你用什么监视器来同步someGetMethod()本身?