我正在尝试将类设为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的东西..
答案 0 :(得分:3)
需要参数的单例在术语上有点矛盾。毕竟,您需要在每次调用时提供参数值,然后考虑如果该值与之前的值不同会发生什么。
我建议你不要在这里使用单身模式。相反,使您的类成为一个完全正常的类 - 但使用依赖注入为所有需要它的类提供对单个已配置实例的引用。
那样: