Javascript - Singleton - 种族条件

时间:2017-08-27 05:37:56

标签: javascript singleton race-condition

我有以下代码来实现单例

const singleton = Symbol();
const singletonEnforcer = Symbol()

class SingletonTest {

  constructor(enforcer) {
    if(enforcer != singletonEnforcer) throw "Cannot construct singleton";
  }

  static get instance() {
    if(!this[singleton]) {
      this[singleton] = new SingletonTest(singletonEnforcer);
    }
    return this[singleton];
  }
}

export default SingletonTest

import SingletonTest from 'singleton-test';
const instance = SingletonTest.instance;

我遇到竞争条件问题,当SingletonTest.instance同时执行两次时,我有两个SingletonTest实例,我该如何解决问题?

0 个答案:

没有答案