-1

Just wondering how to best interpret the synchronized keyword in Java? I know what it does (simply put), it locks a critical section for more than one thread to access using a lock object that every object has. So can I interpret synchronized(this) as a method call where the return value of synchronized is this lock object?

TMOTTM
  • 3,286
  • 6
  • 32
  • 63
  • Answered here: [java syntax: “synchronized (this)”](https://stackoverflow.com/questions/13264726/java-syntax-synchronized-this) – Jaime King Mar 31 '20 at 20:36
  • https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.1 "It computes a reference to an object", finds the associated monitor of that object and performs a lock action on that monitor. – TMOTTM Mar 31 '20 at 21:04

2 Answers2

0

synchronized does not return any value. synchronized(this) locks on this instance, i.e. the lock object is this.

Note that locking on this is considered a bad coding practice.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • From the Java Documentation "computes a reference..." does sound to me like it returns something, just not at the client level. – TMOTTM Apr 26 '20 at 11:14
  • I don't know what do you mean "at client level". In any case synchronized() is not a function, it is a keyword and no, it does not return anything. – m0skit0 Apr 27 '20 at 14:44
0

Imagine this is a key and the synchronized block is a hotelroom. When you get the key, the room is yours and noone else can enter it. When you give the key back, someone else can get the key again to enter the room.

synchronized itself doesn't return anything. It is just a syntax to synchronize threads by using locks.

In our example the threads would be guests, a synchronized block would be a hotelroom and a lock is a key for a room. Any object can be a lock and this is an object.

akuzminykh
  • 4,522
  • 4
  • 15
  • 36
  • The interesting thing would now be to know how "synchronization of threads using locks" works internally. – TMOTTM Apr 26 '20 at 11:13
  • @TMOTTM You can check the internals of any open-souce JVM. In any case modern OS already have APIs for this. – m0skit0 Apr 27 '20 at 14:46