2

受到对给定答案的评论的启发,我尝试创建多线程模式的线程安全实现,它依赖于唯一的键并对它们执行锁定(我的想法来自JB Nizet对这个问题的回答)。

问题

我提供的实施是否可行?

我对 Multiton(或 Singleton)是否通常是好的模式不感兴趣,这会引起讨论。我只想要一个干净且有效的实现。

对比

  • 您必须知道在编译时要创建多少个实例。

优点

  • 没有锁定整个班级或整个地图。并发调用getInstance是可能的。
  • 通过 key 对象获取实例,而不仅仅是无界intor String,因此您可以确保在方法调用后获取非空实例。
  • 线程安全(至少这是我的印象)。

public class Multiton
{
  private static final Map<Enum<?>, Multiton> instances = new HashMap<Enum<?>, Multiton>();

  private Multiton() {System.out.println("Created instance."); }

  /* Can be called concurrently, since it only synchronizes on id */
  public static <KEY extends Enum<?> & MultitionKey> Multiton getInstance(KEY id)
  {
    synchronized (id)
    {
      if (instances.get(id) == null)
        instances.put(id, new Multiton());
    }
    System.out.println("Retrieved instance.");
    return instances.get(id);
  }

  public interface MultitionKey { /* */ }

  public static void main(String[] args) throws InterruptedException
  {
    //getInstance(Keys.KEY_1);
    getInstance(OtherKeys.KEY_A);

    Runnable r = new Runnable() {
      @Override
      public void run() { getInstance(Keys.KEY_1); }
    };

    int size = 100;
    List<Thread> threads = new ArrayList<Thread>();
    for (int i = 0; i < size; i++)
      threads.add(new Thread(r));

    for (Thread t : threads)
      t.start();

    for (Thread t : threads)
      t.join();
  }

  enum Keys implements MultitionKey
  {
    KEY_1;

    /* define more keys */
  }

  enum OtherKeys implements MultitionKey
  {
    KEY_A;

    /* define more keys */
  }
}

我试图防止调整地图大小和滥用我同步的枚举。在我完成之前,这更像是一个概念证明!:)

public class Multiton
{
  private static final Map<MultitionKey, Multiton> instances = new HashMap<MultitionKey, Multiton>((int) (Key.values().length/0.75f) + 1);
  private static final Map<Key, MultitionKey> keyMap;

  static
  {
    Map<Key, MultitionKey> map = new HashMap<Key, MultitionKey>();
    map.put(Key.KEY_1, Keys.KEY_1);
    map.put(Key.KEY_2, OtherKeys.KEY_A);
    keyMap = Collections.unmodifiableMap(map);
  }

  public enum Key {
    KEY_1, KEY_2;
  }

  private Multiton() {System.out.println("Created instance."); }

  /* Can be called concurrently, since it only synchronizes on KEY */
  public static <KEY extends Enum<?> & MultitionKey> Multiton getInstance(Key id)
  {
    @SuppressWarnings ("unchecked")
    KEY key = (KEY) keyMap.get(id);
    synchronized (keyMap.get(id))
    {
      if (instances.get(key) == null)
        instances.put(key, new Multiton());
    }
    System.out.println("Retrieved instance.");
    return instances.get(key);
  }

  private interface MultitionKey { /* */ }

  private enum Keys implements MultitionKey
  {
    KEY_1;

    /* define more keys */
  }

  private enum OtherKeys implements MultitionKey
  {
    KEY_A;

    /* define more keys */
  }
}
4

3 回答 3

3

它绝对不是线程安全的。这是一个简单的例子,说明了很多很多可能出错的事情。

线程 A 正试图放入 key id1。由于 put at ,线程 B 正在调整存储桶表的大小id2。因为它们有不同的同步监视器,所以它们并行地参加比赛。

Thread A                      Thread B
--------                      --------
b = key.hash % map.buckets.size   

                             copy map.buckets reference to local var
                             set map.buckets = new Bucket[newSize]
                             insert keys from old buckets into new buckets

insert into map.buckets[b]

在这个例子中,假设Thread A看到了map.buckets = new Bucket[newSize]修改。不能保证(因为没有发生之前的边缘),但它可能。在这种情况下,它将 (key, value) 对插入到错误的存储桶中。没有人会找到它。

作为一个轻微的变体,如果将引用Thread A复制map.buckets到本地 var 并对其进行所有工作,那么它将插入到正确的存储桶中,但会插入错误的存储桶表;它不会插入到Thread B即将安装的新表中,以供大家查看。如果下一个操作key 1碰巧看到新表(同样,不能保证,但它可能会),那么它不会看到Thread A's操作,因为它们是在一个早已被遗忘的存储桶数组上完成的。

于 2013-08-09T13:57:36.753 回答
2

我会说不可行。

id参数进行同步充满危险——如果他们将其enum用于另一种同步机制怎么办?当然HashMap,正如评论所指出的那样,这不是并发的。

为了演示 - 试试这个:

Runnable r = new Runnable() {
  @Override
  public void run() { 
    // Added to demonstrate the problem.
    synchronized(Keys.KEY_1) {
      getInstance(Keys.KEY_1);
    } 
  }
};

这是一个使用原子而不是同步的实现,因此应该更有效。它比你的要复杂得多,但处理MiltitonIS 中的所有边缘情况很复杂。

public class Multiton {
  // The static instances.
  private static final AtomicReferenceArray<Multiton> instances = new AtomicReferenceArray<>(1000);

  // Ready for use - set to false while initialising.
  private final AtomicBoolean ready = new AtomicBoolean();
  // Everyone who is waiting for me to initialise.
  private final Queue<Thread> waiters = new ConcurrentLinkedQueue<>();
  // For logging (and a bit of linguistic fun).
  private final int forInstance;

  // We need a simple constructor.
  private Multiton(int forInstance) {
    this.forInstance = forInstance;
    log(forInstance, "New");
  }

  // The expensive initialiser.
  public void init() throws InterruptedException {
    log(forInstance, "Init");
    // ... presumably heavy stuff.
    Thread.sleep(1000);

    // We are now ready.
    ready();
  }

  private void ready() {
    log(forInstance, "Ready");
    // I am now ready.
    ready.getAndSet(true);
    // Unpark everyone waiting for me.
    for (Thread t : waiters) {
      LockSupport.unpark(t);
    }
  }

  // Get the instance for that one.
  public static Multiton getInstance(int which) throws InterruptedException {
    // One there already?
    Multiton it = instances.get(which);
    if (it == null) {
      // Lazy make.
      Multiton newIt = new Multiton(which);
      // Successful put?
      if (instances.compareAndSet(which, null, newIt)) {
        // Yes!
        it = newIt;
        // Initialise it.
        it.init();
      } else {
        // One appeared as if by magic (another thread got there first).
        it = instances.get(which);
        // Wait for it to finish initialisation.
        // Put me in its queue of waiters.
        it.waiters.add(Thread.currentThread());
        log(which, "Parking");
        while (!it.ready.get()) {
          // Park me.
          LockSupport.park();
        }
        // I'm not waiting any more.
        it.waiters.remove(Thread.currentThread());
        log(which, "Unparked");
      }
    }

    return it;
  }

  // Some simple logging.
  static void log(int which, String s) {
    log(new Date(), "Thread " + Thread.currentThread().getId() + " for Multiton " + which + " " + s);
  }
  static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  // synchronized so I don't need to make the DateFormat ThreadLocal.

  static synchronized void log(Date d, String s) {
    System.out.println(dateFormat.format(d) + " " + s);
  }

  // The tester class.
  static class MultitonTester implements Runnable {
    int which;

    private MultitonTester(int which) {
      this.which = which;
    }

    @Override
    public void run() {
      try {
        Multiton.log(which, "Waiting");
        Multiton m = Multiton.getInstance(which);
        Multiton.log(which, "Got");
      } catch (InterruptedException ex) {
        Multiton.log(which, "Interrupted");
      }
    }
  }

  public static void main(String[] args) throws InterruptedException {
    int testers = 50;
    int multitons = 50;
    // Do a number of them. Makes n testers for each Multiton.
    for (int i = 1; i < testers * multitons; i++) {
      // Which one to create.
      int which = i / testers;
      //System.out.println("Requesting Multiton " + i);
      new Thread(new MultitonTester(which+1)).start();
    }

  }
}
于 2013-08-09T13:41:28.223 回答
0

我不是 Java 程序员,但是:HashMap并发访问不安全。我可以推荐ConcurrentHashMap

  private static final ConcurrentHashMap<Object, Multiton> instances = new ConcurrentHashMap<Object, Multiton>();

  public static <TYPE extends Object, KEY extends Enum<Keys> & MultitionKey<TYPE>> Multiton getInstance(KEY id)
  {
    Multiton result;
    synchronized (id)
    {
      result = instances.get(id);
      if(result == null)
      {
        result = new Multiton();
        instances.put(id, result);
      }
    }
    System.out.println("Retrieved instance.");
    return result;
  }
于 2013-08-09T13:09:06.627 回答