当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Calling a method from within a synchronized method

问题描述:

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

}

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?

网友答案:

No it can't. A synchronized method is basically the same as:

public void example(){
  synchronized(this){
    //do stuff
  }
}
网友答案:

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(){

}

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.

网友答案:

When a thread enters a Synchronized method a lock occurs, the lock doesn't release until that method returns, which would be after your call to call().

Here is a good article on locks and synchronization: http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html

分享给朋友:
您可能感兴趣的文章:
随机阅读: