- 什么是“非阻塞”并发,它与使用线程的普通并发有何不同?为什么我们不在所有需要并发的场景中都使用非阻塞并发呢?使用非阻塞并发是否有开销?
- 我听说在 Java 中可以使用非阻塞并发。是否存在我们应该使用此功能的特定场景?
- 将这些方法之一用于集合是否有区别或优势?有哪些取舍?
第三季度示例:
class List
{
private final ArrayList<String> list = new ArrayList<String>();
void add(String newValue)
{
synchronized (list)
{
list.add(newValue);
}
}
}
对比
private final ArrayList<String> list = Collections.synchronizedList();
这些问题更多是从学习/理解的角度出发的。感谢关注。
最佳答案
What is Non-blocking Concurrency and how is it different.
正式:
In computer science, non-blocking synchronization ensures that threads competing for a shared resource do not have their execution indefinitely postponed by mutual exclusion. A non-blocking algorithm is lock-free if there is guaranteed system-wide progress; wait-free if there is also guaranteed per-thread progress. (wikipedia)
非正式:非阻塞与阻塞最有利的特性之一是,线程不必被操作系统挂起/唤醒。这样的开销可以达到 1ms 到几个 10ms,因此消除它可能会带来很大的性能提升。在java中,这也意味着你可以选择使用非公平锁,它可以比公平锁有更多的系统吞吐量。
I have heard that this is available in Java. Are there any particular scenarios we should use this feature
是的,从 Java5 开始。实际上,在 Java 中,您基本上应该尽可能地尝试使用 java.util.concurrent 来满足您的需求(这恰好使用了很多非阻塞并发,但在大多数情况下您不必明确担心)。只有当您没有其他选择时,您才应该使用同步包装器(.synchronizedList() 等)或手动 synchronize
关键字。这样一来,您大部分时间都会使用更易于维护、性能更好的应用程序。
当存在大量争用时,非阻塞并发特别有利。当您需要阻塞(公平锁定、事件驱动的东西、具有最大长度的队列等)时,您不能使用它,但如果您不需要,非阻塞并发在大多数情况下往往会表现得更好。
Is there a difference/advantage of using one of these methods for a collection. What are the trade offs
两者具有相同的行为(字节码应该相等)。但我建议使用 Collections.synchronized
因为它更短 = 更小的空间搞砸了!
关于java - 什么是 "non-blocking"并发,它与普通并发有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2824225/