CouchbaseBucketRegistry { public synchronized boolean closeBucket(String bucketName, List<String> clusterNodes) { String bucketId = getBucketId(bucketName, clusterNodes); String clusterId = getClusterId(clusterNodes); if (!openedBuckets.containsKey(bucketId) || !openedClusters.containsKey(clusterId)) { return false; } bucketUsageCounts.put(bucketId, bucketUsageCounts.get(bucketId) - 1); clusterUsageCounts.put(clusterId, clusterUsageCounts.get(clusterId) - 1); Boolean bucketClosed = true; Boolean clusterClosed = true; if (bucketUsageCounts.get(bucketId) == 0) { bucketClosed = openedBuckets.get(bucketId).close(); openedBuckets.remove(bucketId); bucketUsageCounts.remove(bucketId); if (clusterUsageCounts.get(clusterId) == 0) { clusterClosed = openedClusters.get(clusterId).disconnect(); openedClusters.remove(clusterId); clusterUsageCounts.remove(clusterId); } } return bucketClosed && clusterClosed; } CouchbaseBucketRegistry(); synchronized Bucket getBucket(String bucketName, List<String> clusterNodes,
      CouchbaseEnvironmentConfigs configs); synchronized boolean closeBucket(String bucketName, List<String> clusterNodes);  }
@Test public void testCloseBucket() { String bucketName = "bucket"; List<String> clusterNodes = Arrays.asList("cluster"); CouchbaseEnvironmentConfigs configs = new CouchbaseEnvironmentConfigs(); CouchbaseCluster cluster = mock(CouchbaseCluster.class); Bucket bucket = mock(Bucket.class); when(bucket.close()).thenReturn(true).thenReturn(false); when(cluster.openBucket(bucketName)).thenReturn(bucket); when(cluster.disconnect()).thenReturn(true).thenReturn(false); mockStatic(CouchbaseCluster.class); when(CouchbaseCluster.create(any(CouchbaseEnvironment.class), eq(clusterNodes))).thenReturn(cluster); CouchbaseBucketRegistry registry = new CouchbaseBucketRegistry(); int numOfThreads = 10; for (int i = 0; i < numOfThreads; i++) { registry.getBucket(bucketName, clusterNodes, configs); } for (int i = 0; i < numOfThreads; i++) { assertTrue(registry.closeBucket(bucketName, clusterNodes)); } assertFalse(registry.closeBucket(bucketName, clusterNodes)); assertFalse(bucket.close()); }