-3


Recently I had a discussion with a friend about concurrency in java and he asked me as to why is the synchronized keyword either around a block of code or method slow. I answered back saying that it is slow because it contends for an object monitor. Also it gives a happens before guarantee and it has to synchronize all the variables in it's cache with main memory and at the end of the block it has to flush the cache back. It also prevents compiler as well as cpu reordering of instructions. However he said that these do lead to a slowdown but this is not the main reason for performance degradation. Essentially even if there is no contention when a thread hits a synchronized block it switches from user mode to kernel mode and the thread has to save state and then when it leaves the block it has to once again reload the state. I am trying to find literature on the web that describes this but I am unable to find any. I am wondering if anyone can confirm this is correct? Why should java threads enter kernel mode when it hits synchronized and why not before that?This is not the same as the question asked in this link because I am asking about the explicit switch from user mode to kernel mode and it this causes a performance degradation?

Community
  • 1
  • 1
Salil Surendran
  • 2,245
  • 4
  • 27
  • 42

1 Answers1

1

What your friend told is absolutely incorrect.

You were pretty much right about what's so expensive about synchronized. The most difficult part is actually (especially on x86/x86_64 processors) the compare and swap instruction which compares and sets the current thread as the owner of the lock. On x86/x86_64 cmpxchg instruction is used for this and as it reaches the main memory, it's way slower than any regular instruction. Then as you mentioned, memory barriers slow down the caches.

On some other architectures, especially RISC based, usually passive load exclusive/store exclusive are used which are usually much faster. So this may differ from architecture to architecture.

Anyway, Java (and any other language) tries to avoid entering kernel and most mutext implementation only do it after several retries when it's almost clear that the thread need to be suspended.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43