从同步方法中调用方法

从同步方法中调用方法

问题描述:

我面临一个奇怪的问题,这使我想知道同步方法中到底发生了什么.假设有一种方法

I'm facing a strange problem which has made me wonder what exactly happens in a synchronized method. Let's say there is a method

synchronized public void example(){
     //...code
     int i=call(); //calling another method
     //...do something with i 
}

现在,当执行call()方法时,另一个对象可以输入此同步的example()方法吗?因此,当call()返回时,可能会出现一些ConcurrentModificationException吗?为了避免出现问题该怎么办?

Now while the call() method is being executed, can another object enter this synchronized example() method? So when the call() returns, there might be some ConcurrentModificationException? What to do in order to avoid problems?

请注意,在此示例中,如果call()不是私有的或从类中的其他地方调用的,则其他人可以中断您的认为是一个完全同步的过程.

Note that in this example, if call() isn't private or is called from somewhere else in the class, someone else can interrupt what you think is an entirely synchronous process.

synchronized void a(){
    println 'hello'
    b();
    println 'world'
}

void b(){

}

如果您期望"a的所有内容都可以通过同步来保护",那么如果b完全没有副作用,那么如果synchronized void a以外的方法调用b,则该保证将丢失.

If you expect "everything that a does to be guarded by synchronized", then if b has any side-effects at all, that guarantee is lost if methods other than synchronized void a call b.