简体   繁体   English

用Java如何实现同步块?

[英]How are synchronized blocks implemented in Java?

在某些时候线程将争夺监视器,在这一点上应该有一个线程获胜,Java是否使用内置在CPU中的原子CAS操作来实现对这些监视器的获取,如果不行的话?

I don't think so since in the concurrent packages you can find the Atomic* classes which use CAS internally. 我不这么认为,因为在concurrent发包中您可以找到内部使用CAS的Atomic*类。

Another thing is that it depends on what kind of jvm you use. 另一件事是,它取决于您使用哪种类型的jvm。 So in its current form your question is not really answerable apart from telling you that CAS is used elswhere. 因此,按照目前的形式,除了告诉您在其他地方使用CAS之外,您的问题还无法真正回答。

CAS is what makes all concurrency work at the hardware level. CAS使所有并发都在硬件级别起作用。 If you want to change one value in memory across all threads, CAS is the fastest way to do it; 如果要在所有线程中更改内存中的一个值,则CAS是最快的方法。 any other technique is going to use CAS also. 任何其他技术也将使用CAS。 So for quick changes, CAS is the way to go. 因此,对于快速更改,CAS是必经之路。 But if you have 100, or even 5 values to change, you're likely better off using synchronization. 但是,如果要更改100个或什至5个值,最好使用同步。 It'll do one CAS to lock the monitor and another to unlock it, but the rest is normal memory reads and writes which are much faster than CAS. 它将执行一次CAS锁定监视器,然后执行另一次CAS锁定,但其余操作是正常的内存读写,这比CAS快得多。 Of course, you do have the monitor locked, which may hang other threads, slowing your program and possibly wasting CPU. 当然,您确实将监视器锁定了,这可能会挂起其他线程,从而降低程序速度并可能浪费CPU。

A bigger concern is that in Java any CAS (or reading/writing volatiles and synching/unsynching) is accompanied by bringing other threads' views of memory up-to-date. 一个更大的问题是,在Java中,任何CAS(或读/写volatile和同步/不同步)都伴随着其他线程对内存的更新。 When you write a volatile, the threads that read it see all the memory changes made by writing the thread. 当您编写一个volatile时,读取它的线程会看到通过写入该线程所做的所有内存更改。 This involves dumping register values to memory, flushing caches, updating caches, and putting data back into registers. 这涉及将寄存器值转储到内存,刷新缓存,更新缓存以及将数据放回寄存器。 But these costs parallel CAS, so if you've got one figured out, you've got the other figured out too. 但是这些费用与CAS差不多,因此,如果您想出了一个,那么您也想出了另一个。

The basic idea, I think, from the programmers' point of view, is to use volatile or atomic operations for single reads and writes and synchronization for multiples-- if there's no other compelling reason to chose one over the other. 我认为,从程序员的角度来看,基本思想是对单个读写使用易失性或原子操作,对倍数进行同步- 如果没有其他令人信服的理由选择另一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM