簡體   English   中英

如何使線程安全可以接受參數的單例類?

[英]How to make thread safe singleton class which can accepts parameter?

我試圖使一個類成為ThreadSafe Singleton但是以某種方式我無法理解如何使ThreadSafe Singleton類可以接受參數。

下面是我正在使用的該github 鏈接中正在使用的類,該類當前用於建立與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的內容。

就參數而言,需要參數的單例有點矛盾。 畢竟,您需要在每次調用時提供參數值,然后考慮如果該值與先前的值不同會發生什么。

我鼓勵您在這里完全避免使用單例模式。 而是使您的類成為完全正常的類-但使用依賴注入為所有需要它的所有類提供對單個配置實例的引用。

那樣:

  • 單例性質不被強制執行,它只是您的自然需求,只需要一個引用即可。 如果以后需要兩個引用(例如由於某種原因用於不同的Zookeeper實例),則可以僅配置不同的依賴項注入
  • 缺乏全局狀態通常使事情更容易測試。 一種測試可能使用一種配置。 另一項測試可能使用其他測試。 沒有單身,沒有問題。 只需將相關的引用傳遞到被測類的構造函數中即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM