书中Java Concurrency in Practice Brian Goetz 等人:
Context switches are not free; thread scheduling requires manipulating shared data structures in the OS and JVM. The OS and JVMuse the same CPUs your program does; more CPU time spent in JVM and OS code means less is available for your program. But OS and JVM activity is not the only cost of context switches. When a new thread is switched in, the data it needs is unlikely to be in the local processor cache, so a context switch causes a flurry of cache misses, and thus threads run a little more slowly when they are first scheduled. This is one of the reasons that schedulers give each runnable thread a certain minimum time quantum even when many other threads are waiting: it amortizes the cost of the context switch and its consequences over more uninterrupted execution time, improving overall throughput (at some cost to responsiveness).
是否可以在不进行上下文切换(不在另一个线程中切换)的情况下阻塞等待锁定的线程?似乎它可能很有用,因为上下文切换很昂贵。
第二个问题:Java 中的 Thread.sleep() 会触发上下文切换吗?
最佳答案
这是一个不受欢迎的观点:您经常希望发生上下文切换。想象一下,有一种方法可以防止这种情况发生,所以每次需要从 CPU
中取出一个线程实际上会停滞不前,这意味着其他所有人都会有效地等待,例如 queue
;没有机会跑。
快进我们的产品,我们有 pod
有目的的s CPU
绑定(bind)到他们。如果上下文切换会以某种方式被禁用,我们不会喜欢这样。我对(几乎)并发请求的上下文切换惩罚感到满意;换单CPU
提供给 pod
(这在 AWS/OpenShift
等中并不便宜,尤其是当您乘以数百时)。
在某些情况下,可能需要这样的场景,但他们没有制定规则。我知道(并且自己做过)的一个异常(exception)是使用基于 CAS
的自旋锁。 ,如 AtomicInteger
和 friend (在内部有这个构建)。
我很确定通过 CAS
增加会比上下文切换便宜。话虽如此,有LongAdder
在文档中说:
But under high contention, expected throughput of this class is significantly higher, at the expense of higher space consumption.
所以我想根本没有适合所有方法的尺寸。
Thread::sleep
可能会发出上下文切换(并且很可能会发出),但不能保证。至少没有记录到这样做。
关于java - 当一个线程在尝试获取锁后被挂起时,是否总是有上下文切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66357190/