Java Client, Singleton implementation for couchbase

Hi,

Please see below code for singleton instance of Couchbase.

public enum CouchbaseInstance {

INSTANCE;
private Cluster cluster = null;

private final Logger logger = Logger.getLogger(CouchbaseInstance.class);

private CouchbaseInstance() {
    try {
        if (cluster == null) {
            cluster = getCluster();
            logger.info("Couchbase connection created successfully");
        }
    } catch (CouchbaseException ex) {
        logger.error("ERROR while connecting to Couchbase", ex);
    }
}

private synchronized Cluster getCluster() {
    String host = PropertyFileReader.getValue("COUCHBASE_HOST");
    return CouchbaseCluster.create(host);
}

public Bucket getBucket(String bucketName) {
    if (cluster == null) {
        logger.warn("Couchbase cluster is null");
        cluster = getCluster();
    }
    return cluster.openBucket(bucketName);
}

}

and i am doing operations on couchbase like:

Bucket bucket = CouchbaseInstance.INSTANCE.getBucket(“test_bucket”);
bucket.upsert(JsonDocument.create(id, expirySecs, content));

so my question is, is this heavy to call openBucket() every time i do operation or is this a good approach.

Thanks

Anybody, who can help me?

Hi @shams.hq,

You may want to ask this in the Java forum: https://forums.couchbase.com/c/java-sdk

I’m not much of a Java user, but I would say that it’s probably not necessary to open a new bucket every time you’re doing an operation. I don’t think getting a bucket is a very expensive operation if you’ve already got a Cluster object, but I’m not for sure. I’m tagging @subhashni since she knows for sure.

Hi @shams.hq,

It is okay to open buckets that are already open, we cache them on the sdk, but an ideal approach would be to not do it for every operation.