0

Code snippet like below:

List<String> list = new ArrayList<>();

public void addValue(int i) {
    synchronized (list) {
        list.add("list" + i);
    }
}

My question is that what is locked by keyword synchronized.
What will be checked of the list when two threads are asking to execute the code block?
The same question is that I synchronized this but its fields can still be changed.

xuanzhui
  • 1,300
  • 4
  • 12
  • 30

1 Answers1

0

The synchronized block is locked. When the code runs, a thread does not lock the object, instead, it OBTAINS the lock of the list object,(which is a mark word inside the object header) so other thread cannot obtain the same lock. As a result, the code inside the block can only be executed by one thread at the same time.

Shawn Song
  • 301
  • 1
  • 9