Mutual exclusion - How synchronized works? [closed]

孤者浪人 提交于 2019-12-08 14:21:45

问题


As mentioned in answer, synchronized is implemented using compareAndSwap, which is non-blocking algorithm.

  1. On synchronized without using wait(), Does a thread state set to BLOCKED?

  2. Does a thread in BLOCKED & WAITING state consume CPU cycles?


回答1:


As mentioned in answer, synchronized is implemented using compareAndSwap, which is non-blocking algorithm.

I think you are misreading that answer. synchronized is certainly not implemented with the Java-level compareAndSwap call. It will be implemented in native code by the interpreter and JIT in your JVM. Under the covers it might use the compare-and-swap instruction, or it may use something else (atomic test-and-set and atomic exchange are also common - and some platforms don't even have a CAS primitive).

This is definitely not a "non-blocking algorithm" - by definition synchronized implements a type of critical section which implies blocking if a second thread tries to enter the critical section while another thread is inside it.

1) On synchronized without using wait(), Does a thread state set to BLOCKED?

Yes, if a thread is waiting to enter a synchronized section, its state is set to BLOCKED.

2) Does a thread in BLOCKED & WAITING state consume CPU cycles?

Generally no, at least not in an ongoing manner. There is a CPU cost associated with entering and exiting the state1, but once the thread is blocked it is generally held in a non-runnable state until it is awoken when the monitor becomes free, and doesn't use CPU resources during that time.


1 Which is exactly why good implementations will generally "spin" a bit before going to sleep, in case the critical section is short and the holding thread may soon exit - spinning in this case avoids the 1000+ cycle overhead of making the transition to sleep (which involves the OS, etc).



来源:https://stackoverflow.com/questions/47851595/mutual-exclusion-how-synchronized-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!