问题
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?
回答1:
No it can't. A synchronized method is basically the same as:
public void example(){
synchronized(this){
//do stuff
}
}
回答2:
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
.
回答3:
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
来源:https://stackoverflow.com/questions/6961848/calling-a-method-from-within-a-synchronized-method