java - 阻塞锁与非阻塞锁

标签 java multithreading concurrency concurrent-programming

我在想:如果您有 2 个线程执行需要同步的 FAST 操作,非阻塞方法不是比阻塞/上下文切换方法更快/更好吗?

我所说的非阻塞是指:

同时(真){ 如果(checkAndGetTheLock())中断;

我唯一能想到的就是如果你有太多线程围绕着锁循环,就会出现饥饿(CPU 耗尽)。

我如何平衡一种方法与另一种方法?

最佳答案

以下是Java 并发实践关于这个主题的内容:

The JVM can implement blocking either via spin-waiting (repeatedly trying to acquire the lock until it succeeds) or bysuspending the blocked thread through the operating system. Which is more efficient depends on the relationship between context switch overhead and the time until the lock becomes available; spin-waiting is preferable for short waits and suspension is preferable for long waits. Some JVMs choose between the two adaptively based on profiling data of past wait times, but most just suspend threads waiting for a lock.

还有(这是 IMO 最重要的一点):

Don't worry excessively about the cost of uncontended synchronization. The basic mechanism is already quite fast, and JVMs can perform additional optimizations that further reduce or eliminate the cost. Instead, focus optimization efforts on areas where lock contention actually occurs.

关于java - 阻塞锁与非阻塞锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9469460/

相关文章:

java - ZoneId 和 LocalDateTime

java - 使用 maven + yguard

java - 线索消失得无影无踪

java - ForkJoinPool中的辅助线程是守护程序线程吗?

java - 在Java中将十进制转换为罗马数字?

java - 在 Android 中正确实现 PagerAdapter

java - 如何在线程中使用定时器

Visual Studio Code 中的 Python 异步/线程调试

c# - Thread.Abort() 导致应用程序被杀死

java - 正确设置简单的服务器端缓存