并发LinkedHashSet


  LinkedHashSet 是一个也可以保持有序的集合。为了使这个线程安全,我们可以用 Collections.synchronizedSet() 包装它。然而,这不是一个好的选择,因为迭代仍然会很快失败。我们不能迭代的线程安全的 LinkedHashSet 有什么意义呢?
在本期通讯中,我们尝试创建一个行为类似于 LinkedHashSet 的并发集合,但具有最少的锁定和弱一致性迭代。

// Maven: eu.javaspecialists.books.dynamicproxies:core:2.0.0
import eu.javaspecialists.books.dynamicproxies.*;

import java.util.*;

public class DynamicProxiesDemo {
  public static void main(String... args) {
    Set<String> angrySet = Proxies.castProxy(
        Set.class,
        (p, m, a) -> {
          throw new UnsupportedOperationException(
              m.getName() +
"() not implemented");
        }
    );

    Set<String> set = Proxies.adapt(
        Set.class,
// target interface
        angrySet,
// adaptee
        new ConcurrentLinkedReducedHashSet<>()
// adapter
    );
    set.add(
"hello");
    set.add(
"world");
    Iterator<String> it = set.iterator();
    set.add(
"Goodbye");
    while (it.hasNext()) {
      String next = it.next();
      System.out.println(next);
    }
    set.clear();
    set.addAll(List.of(
"one")); // UnsupportedOperationException
  }
}    

不能保证这将有多快,也不能保证它是否有效。我很高兴看到使用标准 JDK 类的更好解决方案。
详细点击标题见原文

banq:建议使用chronicle queue或disruptor:前者使用磁盘文件作为两个线程共享,后者使用内存环形作为两个线程共享