java - 当一个线程在尝试获取锁后被挂起时,是否总是有上下文切换?

标签 java multithreading concurrency

书中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/

相关文章:

multithreading - goroutine 或多线程在 golang 中不起作用

Java 正则表达式模式太长?

java - 创建比请求更多的线程

c - 信号量的3个线程和消费者生产者问题

java - 从Handler迁移到ScheduledExecutorService进行调度

multithreading - Julia线程中的变量是循环线程本地的吗?

java - Android Studio - 尝试签署 facebook 或 google 时 Firebase 返回 null

java - 是否可以在 java 应用程序 Netbeans 中使用 Iframe 网页

java - 如何从该方法中获取方法名称?

java - 如何使用wait()和notifyAll()在GUI类和逻辑线程之间进行通信