-1
public int synchronizedBlockGet() {
    synchronized( this ) {
        return i;
    }
}

I have come across this code while reading some article. what is synchronized ? a class , or method or interface ? Please explain.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

2 Answers2

1

Synchronized or in general synchronization come when you are dealing with threads. For example, let's say there are 2 threads in you program. Both of these threads are using the same object. (Consider a scenario where one thread is writing to an ArrayList and the other one is reading from it). It those cases, we have to ensure that the other thread don't do a read or a write while a thread is writing to the list. This is because, a write to a list will consist of at least 3 steps

  1. read from memory
  2. modify the object(list)
  3. write back to the memory.

In order to make sure that these threads don't intercept and will not cause inconsistencies, we use the concept of thread synchronization.

There are several ways of achieving synchronization including synchronized methods and synchronized blocks. The code you have provided is a synchronized block.

public int synchronizedBlockGet() {
    synchronized( this ) {
        return i;
    }
}

Here what happens is, once a thread is inside the synchronizedBlockGet method, it will lock the entire object(called acquiring the lock of the object) where the above method is. synchronized(this) means that the current thread will lock the entire object. No other thread can therefore access this object until the current thread leave the synchronized block and release the object. Even though the example you have given is not a necessary situation of synchronization, the thing that happens behind is the same.

Imesha Sudasingha
  • 3,462
  • 1
  • 23
  • 34
0

Its a keyword and it will allow only single thread at a time to enter into the block.

It will achieve this by acquiring lock on this object.

kakurala
  • 824
  • 6
  • 15