0

Why I need to pass "this" when Im using synchronized block? what the purpose of the partemer of the synchronized?

Shelef
  • 3,707
  • 6
  • 23
  • 28

5 Answers5

0

Because synchronized needs an object to lock on. this is as convenient as any, or you could say Object lock = new Object() and synchronize on lock.

Alternatively you could mark your methods as synchronized.

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
0

Java synchronized block construct takes an object in parentheses. "this" is the instance of which method is called on. The object taken in the parentheses by the synchronized construct is called a monitor object. The code is said to be synchronized on the monitor object. A synchronized instance method uses the object it belongs to as monitor object.

Only one thread can execute inside a Java code block synchronized on the same monitor object.

Abhishek Kumar
  • 229
  • 1
  • 5
0

The synchronization will be done on the object you specify, meaning if two threads synchronize on the same object, only one can run the code block at one time.

It can be any object, though it will often be this.

This enables you to synchronize on different objects in the same class, for example.

DanneJ
  • 358
  • 1
  • 9
0

syntex is synchronized(objectLock) { } not necessorily this, we need to pass an object, to which we want to give exclusive access in case of multiple threads are trying to run the same synchronized block. in this way, if at any point of time, 2 or more thread trying for access of synchronized block, the object passed ('this' in this case) will have exclusive access of the block, unless the block excution is finished, no one else can access that block.

Ankit
  • 6,554
  • 6
  • 49
  • 71
0

Synchronize uses an object reference to lock on, a monitor object. Each resource that you want to protect from simultaneous access should have its own monitor object. The easiest way to do this is often to use this.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82