问题描述:

I know about the synchronized keyword, but I want to make sure that I have a clear understanding.

So, if I don't use the synchronized keyword, an instance variable may be overwritten by two threads, but if I do use the synchronized keyword only 1 thread may enter the method at a time. Right?

网友答案:

If two threads enter an un-synchronized method and update some shared state, then it can lead to inconsistencies.

public synchronized void method(){ 
      //only one thread will be able to enter (IF SAME INSTANCE)
}

But it also establishes a happens-before relationship. This is visibility part of multithreading.

Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second.

Happens-before JLS.

网友答案:

if I don't use the synchronized keyword, an instance variable may be overwritten by two threads

it won't be "overwritten" but it can be executed by two threads simultaneously, leading to possible inconsistencies if it is not designed to handle such a situation.

if I do use the synchronized keyword only 1 thread may enter the method at a time.

That is correct if you make the method synchronized: that keyword provides a certain number of guarantees, including mutual exclusion.

相关阅读:
Top