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? I am asking about the explicit switch from user mode to kernel mode and it this causes a performance degradation?