如何使线程安全的单例类可以接受参数?

时间:2014-02-13 22:58:55

标签: java thread-safety singleton apache-zookeeper apache-curator

我正在尝试将类设为ThreadSafe Singleton,但不知怎的,我无法理解如何使ThreadSafe Singleton类可以接受参数。

以下是我正在使用的github link中使用的类,我目前正在使用它与Zookeeper建立连接 -

public class LeaderLatchExample {

    private CuratorFramework client;
    private String latchPath;
    private String id;
    private LeaderLatch leaderLatch;

    public LeaderLatchExample(String connString, String latchPath, String id) {
        client = CuratorFrameworkFactory.newClient(connString, new ExponentialBackoffRetry(1000, Integer.MAX_VALUE));
        this.id = id;
        this.latchPath = latchPath;
    }

    public void start() throws Exception {
        client.start();
        client.getZookeeperClient().blockUntilConnectedOrTimedOut();
        leaderLatch = new LeaderLatch(client, latchPath, id);
        leaderLatch.start();
    }

    public boolean isLeader() {
        return leaderLatch.hasLeadership();
    }

    public Participant currentLeader() throws Exception {
        return leaderLatch.getLeader();
    }

    public void close() throws IOException {
        leaderLatch.close();
        client.close();
    }

    public CuratorFramework getClient() {
        return client;
    }

    public String getLatchPath() {
        return latchPath;
    }

    public String getId() {
        return id;
    }

    public LeaderLatch getLeaderLatch() {
        return leaderLatch;
    }
}

这就是我调用上述类的方式 -

public static void main(String[] args) throws Exception {
        String latchPath = "/latch";
        String connStr = "10.12.136.235:2181";
        LeaderLatchExample node1 = new LeaderLatchExample(connStr, latchPath, "node-1"); // this I will be doing only one time at just the initialization time
        node1.start();

        System.out.println("now node-1 think the leader is " + node1.currentLeader());
}

现在我需要的是如果我在程序中的任何类中调用以下两个方法,我应该能够获得它的实例。所以我想把上面的类作为一个线程安全单例,以便我可以在我的所有java程序中访问这两个方法。

isLeader()
getClient()

如何将上面的类设置为ThreadSafe单例,然后在我的所有类中使用isLeader()getClient()来查看谁是领导者并获取客户端实例..

我只需要在初始化时执行此操作,一旦完成,我应该能够在所有类中使用isLeader()getClient()。这可能吗?

// this line I will be doing only one time at just the initialization time
LeaderLatchExample node1 = new LeaderLatchExample(connStr, latchPath, "node-1");
node1.start();

这更像Java问题而不是Zookeeper的东西..

1 个答案:

答案 0 :(得分:3)

需要参数的单例在术语上有点矛盾。毕竟,您需要在每次调用时提供参数值,然后考虑如果该值与之前的值不同会发生什么。

我建议你不要在这里使用单身模式。相反,使您的类成为一个完全正常的类 - 但使用依赖注入为所有需要它的类提供对单个已配置实例的引用。

那样:

  • 单独性质不会被强制执行,它只是你自然的一部分需要一个引用。如果稍后您需要两个引用(例如,由于某种原因对于不同的Zookeeper实例),您可以只是以不同的方式配置依赖注入
  • 缺乏全球状态通常会使事情变得更容易测试。一个测试可能使用一个配置;另一个测试可能会使用另一个测试。没有单身,没问题。只需将相关引用传递给被测试类的构造函数即可。
相关问题