diff --git a/curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java b/curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java index 1007b5988..108bc3125 100644 --- a/curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java +++ b/curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java @@ -34,7 +34,6 @@ import org.apache.curator.utils.DefaultZookeeperFactory; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZookeeperFactory; -import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; @@ -47,11 +46,11 @@ public class CuratorZookeeperClient implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final ConnectionState state; - private final AtomicReference retryPolicy = new AtomicReference(); + private final AtomicReference retryPolicy = new AtomicReference<>(); private final int connectionTimeoutMs; private final int waitForShutdownTimeoutMs; private final AtomicBoolean started = new AtomicBoolean(false); - private final AtomicReference tracer = new AtomicReference(new DefaultTracerDriver()); + private final AtomicReference tracer = new AtomicReference<>(new DefaultTracerDriver()); /** * @@ -155,13 +154,12 @@ public CuratorZookeeperClient( RetryPolicy retryPolicy, boolean canBeReadOnly) { if (sessionTimeoutMs < connectionTimeoutMs) { - log.warn(String.format( - "session timeout [%d] is less than connection timeout [%d]", - sessionTimeoutMs, connectionTimeoutMs)); + log.warn( + "session timeout [{}] is less than connection timeout [{}]", sessionTimeoutMs, connectionTimeoutMs); } - retryPolicy = Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null"); - ensembleProvider = Preconditions.checkNotNull(ensembleProvider, "ensembleProvider cannot be null"); + Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null"); + Preconditions.checkNotNull(ensembleProvider, "ensembleProvider cannot be null"); this.connectionTimeoutMs = connectionTimeoutMs; this.waitForShutdownTimeoutMs = waitForShutdownTimeoutMs; @@ -213,7 +211,7 @@ public boolean isConnected() { /** * This method blocks until the connection to ZK succeeds. Use with caution. The block - * will timeout after the connection timeout (as passed to the constructor) has elapsed + * will time out after the connection timeout (as passed to the constructor) has elapsed * * @return true if the connection succeeded, false if not * @throws InterruptedException interrupted while waiting @@ -229,7 +227,7 @@ public boolean blockUntilConnectedOrTimedOut() throws InterruptedException { trace.commit(); boolean localIsConnected = state.isConnected(); - log.debug("blockUntilConnectedOrTimedOut() end. isConnected: " + localIsConnected); + log.debug("blockUntilConnectedOrTimedOut() end. isConnected: {}", localIsConnected); return localIsConnected; } @@ -252,7 +250,7 @@ public void start() throws Exception { /** * Close the client. * - * Same as {@link #close(int) } using the timeout set at construction time. + *

Same as {@link #close(int) } using the timeout set at construction time.

* * @see #close(int) */ @@ -403,12 +401,7 @@ public void internalBlockUntilConnectedOrTimedOut() throws InterruptedException throw new IllegalStateException("Client is not started or has been closed"); } final CountDownLatch latch = new CountDownLatch(1); - Watcher tempWatcher = new Watcher() { - @Override - public void process(WatchedEvent event) { - latch.countDown(); - } - }; + final Watcher tempWatcher = event -> latch.countDown(); state.addParentWatcher(tempWatcher); long startTimeMs = System.currentTimeMillis(); diff --git a/curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java b/curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java index 44aac9bde..9ff1ea24e 100644 --- a/curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java +++ b/curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java @@ -66,7 +66,7 @@ protected long getSleepTimeMs(int retryCount, long elapsedTimeMs) { // copied from Hadoop's RetryPolicies.java long sleepMs = (long) baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1))); if (sleepMs > maxSleepMs) { - log.warn(String.format("Sleep extension too large (%d). Pinning to %d", sleepMs, maxSleepMs)); + log.warn("Sleep extension too large ({}). Pinning to {}", sleepMs, maxSleepMs); sleepMs = maxSleepMs; } return sleepMs; @@ -74,7 +74,7 @@ protected long getSleepTimeMs(int retryCount, long elapsedTimeMs) { private static int validateMaxRetries(int maxRetries) { if (maxRetries > MAX_RETRIES_LIMIT) { - log.warn(String.format("maxRetries too large (%d). Pinning to %d", maxRetries, MAX_RETRIES_LIMIT)); + log.warn("maxRetries too large ({}). Pinning to {}", maxRetries, MAX_RETRIES_LIMIT); maxRetries = MAX_RETRIES_LIMIT; } return maxRetries; diff --git a/curator-examples/src/main/java/cache/CuratorCacheExample.java b/curator-examples/src/main/java/cache/CuratorCacheExample.java index bb9aa9118..2160b6a16 100644 --- a/curator-examples/src/main/java/cache/CuratorCacheExample.java +++ b/curator-examples/src/main/java/cache/CuratorCacheExample.java @@ -44,11 +44,10 @@ public static void main(String[] args) throws Exception { // there are several ways to set a listener on a CuratorCache. You can watch for individual events // or for all events. Here, we'll use the builder to log individual cache actions CuratorCacheListener listener = CuratorCacheListener.builder() - .forCreates(node -> System.out.println(String.format("Node created: [%s]", node))) - .forChanges((oldNode, node) -> System.out.println( - String.format("Node changed. Old: [%s] New: [%s]", oldNode, node))) - .forDeletes(oldNode -> - System.out.println(String.format("Node deleted. Old value: [%s]", oldNode))) + .forCreates(node -> System.out.printf("Node created: [%s]%n", node)) + .forChanges((oldNode, node) -> + System.out.printf("Node changed. Old: [%s] New: [%s]%n", oldNode, node)) + .forDeletes(oldNode -> System.out.printf("Node deleted. Old value: [%s]%n", oldNode)) .forInitialized(() -> System.out.println("Cache initialized")) .build(); diff --git a/curator-examples/src/main/java/pubsub/SubPubTest.java b/curator-examples/src/main/java/pubsub/SubPubTest.java index 727b76b25..f67278fc7 100644 --- a/curator-examples/src/main/java/pubsub/SubPubTest.java +++ b/curator-examples/src/main/java/pubsub/SubPubTest.java @@ -143,7 +143,7 @@ private void publishSomething(Publisher publisher) { .mapToObj(__ -> new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports))) .collect(Collectors.toList()); - System.out.println(String.format("Publishing %d instances", instances.size())); + System.out.printf("Publishing %d instances%n", instances.size()); publisher.publishInstances(instances); break; } @@ -161,7 +161,7 @@ private void publishSomething(Publisher publisher) { .mapToObj(__ -> new LocationAvailable( nextId(), random(Priority.values()), random(locations), random(durations))) .collect(Collectors.toList()); - System.out.println(String.format("Publishing %d locationsAvailable", locationsAvailable.size())); + System.out.printf("Publishing %d locationsAvailable%n", locationsAvailable.size()); publisher.publishLocationsAvailable(random(groups), locationsAvailable); break; } @@ -179,7 +179,7 @@ private void publishSomething(Publisher publisher) { .mapToObj(__ -> new UserCreated( nextId(), random(Priority.values()), random(locations), random(positions))) .collect(Collectors.toList()); - System.out.println(String.format("Publishing %d usersCreated", usersCreated.size())); + System.out.printf("Publishing %d usersCreated%n", usersCreated.size()); publisher.publishUsersCreated(random(groups), usersCreated); break; } @@ -187,8 +187,8 @@ private void publishSomething(Publisher publisher) { } private ModeledCacheListener generalListener() { - return (type, path, stat, model) -> System.out.println( - String.format("Subscribed %s @ %s", model.getClass().getSimpleName(), path)); + return (type, path, stat, model) -> + System.out.printf("Subscribed %s @ %s%n", model.getClass().getSimpleName(), path); } @SafeVarargs diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkBase.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkBase.java index 1b6c461b2..cc98a0957 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkBase.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkBase.java @@ -113,7 +113,7 @@ final ZooKeeper getZooKeeper() throws Exception { protected final void internalSync(CuratorFrameworkBase impl, String path, Object context) { BackgroundOperation operation = new BackgroundSyncImpl(impl, context); - processBackgroundOperation(new OperationAndData(operation, path, null, null, context, null), null); + processBackgroundOperation(new OperationAndData<>(operation, path, null, null, context, null), null); } abstract byte[] getDefaultData(); diff --git a/curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java b/curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java index 44f199d97..eaef6e061 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java @@ -82,7 +82,7 @@ public void forEach(Consumer function) { function.accept(entry.listener); } catch (Throwable e) { ThreadUtils.checkInterrupted(e); - log.error(String.format("Listener (%s) threw an exception", entry.listener), e); + log.error("Listener ({}) threw an exception", entry.listener, e); } }); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java index c751296df..e39be3014 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java @@ -23,7 +23,6 @@ import java.io.Closeable; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; @@ -57,13 +56,13 @@ public class ConnectionStateManager implements Closeable { } private final Logger log = LoggerFactory.getLogger(getClass()); - private final BlockingQueue eventQueue = new ArrayBlockingQueue(QUEUE_SIZE); + private final BlockingQueue eventQueue = new ArrayBlockingQueue<>(QUEUE_SIZE); private final CuratorFramework client; private final int sessionTimeoutMs; private final int sessionExpirationPercent; private final AtomicBoolean initialConnectMessageSent = new AtomicBoolean(false); private final ExecutorService service; - private final AtomicReference state = new AtomicReference(State.LATENT); + private final AtomicReference state = new AtomicReference<>(State.LATENT); private final UnaryListenerManager listeners; // guarded by sync @@ -80,9 +79,9 @@ private enum State { } /** - * @param client the client - * @param threadFactory thread factory to use or null for a default - * @param sessionTimeoutMs the ZK session timeout in milliseconds + * @param client the client + * @param threadFactory thread factory to use or null for a default + * @param sessionTimeoutMs the ZK session timeout in milliseconds * @param sessionExpirationPercent percentage of negotiated session timeout to use when simulating a session timeout. 0 means don't simulate at all */ public ConnectionStateManager( @@ -96,11 +95,11 @@ public ConnectionStateManager( } /** - * @param client the client - * @param threadFactory thread factory to use or null for a default - * @param sessionTimeoutMs the ZK session timeout in milliseconds + * @param client the client + * @param threadFactory thread factory to use or null for a default + * @param sessionTimeoutMs the ZK session timeout in milliseconds * @param sessionExpirationPercent percentage of negotiated session timeout to use when simulating a session timeout. 0 means don't simulate at all - * @param managerFactory manager factory to use + * @param managerFactory manager factory to use */ public ConnectionStateManager( CuratorFramework client, @@ -124,12 +123,9 @@ public ConnectionStateManager( public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); - service.submit(new Callable() { - @Override - public Object call() throws Exception { - processEvents(); - return null; - } + service.submit(() -> { + processEvents(); + return null; }); } @@ -173,7 +169,7 @@ public synchronized boolean setToSuspended() { /** * Post a state change. If the manager is already in that state the change - * is ignored. Otherwise the change is queued for listeners. + * is ignored. Otherwise, the change is queued for listeners. * * @param newConnectionState new state * @return true if the state actually changed, false if it was already at that state @@ -228,7 +224,7 @@ public synchronized boolean isConnected() { } private void postState(ConnectionState state) { - log.info("State change: " + state); + log.info("State change: {}", state); notifyAll(); @@ -265,7 +261,7 @@ private void processEvents() { && client.getZookeeperClient().isConnected()) { // CURATOR-525 - there is a race whereby LOST is sometimes set after the connection has been // repaired - // this "hack" fixes it by forcing the state to RECONNECTED + // this "hack" fixes it by forcing the state to "RECONNECTED" log.warn("ConnectionState is LOST but isConnected() is true. Forcing RECONNECTED."); addStateChange(ConnectionState.RECONNECTED); } @@ -286,9 +282,10 @@ private void checkSessionExpiration() { startOfSuspendedEpoch = System.currentTimeMillis(); // reset startOfSuspendedEpoch to avoid spinning on this session // expiration injection CURATOR-405 - log.warn(String.format( - "Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: %d. Adjusted session timeout ms: %d", - elapsedMs, useSessionTimeoutMs)); + log.warn( + "Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: {}. Adjusted session timeout ms: {}", + elapsedMs, + useSessionTimeoutMs); try { if (lastExpiredInstanceIndex == client.getZookeeperClient().getInstanceIndex()) { // last expiration didn't work for this instance, so event thread is dead and a reset is needed. diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java index d64f099df..15a08d459 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java @@ -81,7 +81,7 @@ public DistributedAtomicValue( * @throws Exception ZooKeeper errors */ public AtomicValue get() throws Exception { - MutableAtomicValue result = new MutableAtomicValue(null, null, false); + MutableAtomicValue result = new MutableAtomicValue<>(null, null, false); getCurrentValue(result, new Stat()); result.postValue = result.preValue; result.succeeded = true; @@ -119,16 +119,14 @@ public void forceSet(byte[] newValue) throws Exception { */ public AtomicValue compareAndSet(byte[] expectedValue, byte[] newValue) throws Exception { Stat stat = new Stat(); - MutableAtomicValue result = new MutableAtomicValue(null, null, false); + MutableAtomicValue result = new MutableAtomicValue<>(null, null, false); boolean createIt = getCurrentValue(result, stat); if (!createIt && Arrays.equals(expectedValue, result.preValue)) { try { client.setData().withVersion(stat.getVersion()).forPath(path, newValue); result.succeeded = true; result.postValue = newValue; - } catch (KeeperException.BadVersionException dummy) { - result.succeeded = false; - } catch (KeeperException.NoNodeException dummy) { + } catch (KeeperException.BadVersionException | KeeperException.NoNodeException dummy) { result.succeeded = false; } } else { @@ -146,14 +144,9 @@ public AtomicValue compareAndSet(byte[] expectedValue, byte[] newValue) * @throws Exception ZooKeeper errors */ public AtomicValue trySet(final byte[] newValue) throws Exception { - MutableAtomicValue result = new MutableAtomicValue(null, null, false); + MutableAtomicValue result = new MutableAtomicValue<>(null, null, false); - MakeValue makeValue = new MakeValue() { - @Override - public byte[] makeFrom(byte[] previous) { - return newValue; - } - }; + MakeValue makeValue = previous -> newValue; tryOptimistic(result, makeValue); if (!result.succeeded() && (mutex != null)) { tryWithMutex(result, makeValue); @@ -181,7 +174,7 @@ public boolean initialize(byte[] value) throws Exception { } AtomicValue trySet(MakeValue makeValue) throws Exception { - MutableAtomicValue result = new MutableAtomicValue(null, null, false); + MutableAtomicValue result = new MutableAtomicValue<>(null, null, false); tryOptimistic(result, makeValue); if (!result.succeeded() && (mutex != null)) { @@ -204,7 +197,7 @@ RuntimeException createCorruptionException(byte[] bytes) { str.append("0x").append(Integer.toHexString((b & 0xff))); } str.append(']'); - return new RuntimeException(String.format("Corrupted data for node \"%s\": %s", path, str.toString())); + return new RuntimeException(String.format("Corrupted data for node \"%s\": %s", path, str)); } private boolean getCurrentValue(MutableAtomicValue result, Stat stat) throws Exception { @@ -284,11 +277,9 @@ private boolean tryOnce(MutableAtomicValue result, MakeValue makeValue) } result.postValue = Arrays.copyOf(newValue, newValue.length); success = true; - } catch (KeeperException.NodeExistsException e) { - // do Retry - } catch (KeeperException.BadVersionException e) { - // do Retry - } catch (KeeperException.NoNodeException e) { + } catch (KeeperException.NodeExistsException + | KeeperException.BadVersionException + | KeeperException.NoNodeException e) { // do Retry } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.java index b6dd69dad..747a9d6b0 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.java @@ -21,7 +21,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.ArrayList; @@ -30,6 +29,7 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import javax.annotation.Nonnull; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.PathUtils; import org.apache.curator.utils.ZKPaths; @@ -162,14 +162,9 @@ protected List getChildrenForEntering() throws Exception { return client.getChildren().forPath(barrierPath); } + @Nonnull private List filterAndSortChildren(List children) { - Iterable filtered = Iterables.filter(children, new Predicate() { - @Override - public boolean apply(String name) { - return !name.equals(READY_NODE); - } - }); - + Iterable filtered = Iterables.filter(children, name -> !name.equals(READY_NODE)); ArrayList filteredList = Lists.newArrayList(filtered); Collections.sort(filteredList); return filteredList; @@ -191,7 +186,7 @@ private boolean internalLeave(long startMs, boolean hasMaxWait, long maxWaitMs) children = Lists.newArrayList(); } children = filterAndSortChildren(children); - if ((children == null) || (children.size() == 0)) { + if (children.isEmpty()) { break; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java index 2aaa8cc47..d4821a3d9 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java @@ -447,7 +447,7 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex break; default: // An unknown event, probably an error of some sort like connection loss. - LOG.info(String.format("Unknown event %s", event)); + LOG.info("Unknown event {}", event); // Don't produce an initialized event on error; reconnect can fix this. outstandingOps.decrementAndGet(); return; diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharder.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharder.java index 47b073dbe..86220b68b 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharder.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharder.java @@ -238,15 +238,15 @@ private void checkThreshold() { if (addAQueueIfLeader && leaderLatch.hasLeadership()) { if (queues.size() < policies.getMaxQueues()) { - log.info(String.format( - "Adding a queue due to exceeded threshold. Queue Size: %d - Threshold: %d", - size, policies.getNewQueueThreshold())); + log.info( + "Adding a queue due to exceeded threshold. Queue Size: {} - Threshold: {}", + size, + policies.getNewQueueThreshold()); addNewQueueIfNeeded(null); } else { - log.warn(String.format( - "Max number of queues (%d) reached. Consider increasing the max.", - policies.getMaxQueues())); + log.warn( + "Max number of queues ({}) reached. Consider increasing the max.", policies.getMaxQueues()); } } } catch (Exception e) { diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/watch/PersistentWatcher.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/watch/PersistentWatcher.java index d03e9d9b4..e8d191c46 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/watch/PersistentWatcher.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/watch/PersistentWatcher.java @@ -100,7 +100,7 @@ public void close() { client.watchers().remove(watcher).guaranteed().inBackground().forPath(basePath); } catch (Exception e) { ThreadUtils.checkInterrupted(e); - log.debug(String.format("Could not remove watcher for path: %s", basePath), e); + log.debug("Could not remove watcher for path: {}", basePath, e); } } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestEventOrdering.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestEventOrdering.java index 3f4b01fea..14d0d539f 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestEventOrdering.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestEventOrdering.java @@ -77,32 +77,28 @@ public void testEventOrdering() throws Exception { cache = newCache(client, "/root", events); final Random random = new Random(); - final Callable task = new Callable() { - @Override - public Void call() throws Exception { - for (int i = 0; i < ITERATIONS; ++i) { - String node = "/root/" + random.nextInt(NODE_QTY); - try { - switch (random.nextInt(3)) { - default: - case 0: - client.create().forPath(node); - break; - - case 1: - client.setData().forPath(node, "new".getBytes()); - break; - - case 2: - client.delete().forPath(node); - break; - } - } catch (KeeperException ignore) { - // ignore + final Callable task = () -> { + for (int i = 0; i < ITERATIONS; ++i) { + String node = "/root/" + random.nextInt(NODE_QTY); + try { + switch (random.nextInt(3)) { + case 0: + client.create().forPath(node); + break; + + case 1: + client.setData().forPath(node, "new".getBytes()); + break; + + case 2: + client.delete().forPath(node); + break; } + } catch (KeeperException ignore) { + // ignore } - return null; } + return null; }; final CountDownLatch latch = new CountDownLatch(THREAD_QTY); @@ -125,7 +121,7 @@ public Void call() throws Exception { List localEvents = Lists.newArrayList(); int eventSuggestedQty = 0; - while (events.size() > 0) { + while (!events.isEmpty()) { Event event = timing.takeFromQueue(events); localEvents.add(event); eventSuggestedQty += (event.eventType == EventType.ADDED) ? 1 : -1; @@ -137,7 +133,6 @@ public Void call() throws Exception { String.format("actual %s expected %s:\n %s", actualQty, eventSuggestedQty, asString(localEvents))); } finally { executorService.shutdownNow(); - //noinspection ThrowFromFinallyBlock executorService.awaitTermination(timing.milliseconds(), TimeUnit.MILLISECONDS); CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheRandomTree.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheRandomTree.java index 13c30e66e..e3d35e220 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheRandomTree.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheRandomTree.java @@ -177,8 +177,7 @@ private void doTestGiantRandomDeepTree() throws Exception { // Typical stats for this test: maxDepth: 10, adds: 349, removals: 198, updates: 320 // We get more adds than removals because removals only happen if we're at a leaf. - System.out.println( - String.format("maxDepth: %s, adds: %s, removals: %s, updates: %s", maxDepth, adds, removals, updates)); + System.out.printf("maxDepth: %s, adds: %s, removals: %s, updates: %s%n", maxDepth, adds, removals, updates); assertNoMoreEvents(); } diff --git a/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperMain.java b/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperMain.java index 74d39daf2..175e473cb 100644 --- a/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperMain.java +++ b/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperMain.java @@ -226,9 +226,9 @@ public void start(QuorumPeerConfigBuilder configBuilder) { runFromConfig(configBuilder.buildConfig()); } catch (Exception e) { log.error( - String.format( - "From testing server (random state: %s) for instance: %s", - configBuilder.isFromRandom(), configBuilder.getInstanceSpec()), + "From testing server (random state: {}) for instance: {}", + configBuilder.isFromRandom(), + configBuilder.getInstanceSpec(), e); } }, diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryResource.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryResource.java index 73f804d1c..fb995d2e0 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryResource.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryResource.java @@ -34,7 +34,6 @@ import javax.ws.rs.core.Response; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.curator.x.discovery.details.InstanceProvider; import org.apache.curator.x.discovery.server.entity.ServiceInstances; import org.apache.curator.x.discovery.server.entity.ServiceNames; import org.slf4j.Logger; @@ -109,7 +108,6 @@ public Response removeService(@PathParam("name") String name, @PathParam("id") S try { ServiceInstance instance = context.getServiceDiscovery().queryForInstance(name, id); if (instance != null) { - //noinspection unchecked context.getServiceDiscovery().unregisterService(instance); } } catch (Exception e) { @@ -157,10 +155,10 @@ public Response getAll(@PathParam("name") String name) { try { Collection> instances = context.getServiceDiscovery().queryForInstances(name); - return Response.ok(new ServiceInstances(instances)).build(); + return Response.ok(new ServiceInstances<>(instances)).build(); } catch (Exception e) { ThreadUtils.checkInterrupted(e); - log.error(String.format("Trying to get instances from service (%s)", name), e); + log.error("Trying to get instances from service ({})", name, e); return Response.serverError().build(); } } @@ -172,19 +170,14 @@ public Response getAny(@PathParam("name") String name) { try { final List> instances = Lists.newArrayList(context.getServiceDiscovery().queryForInstances(name)); - ServiceInstance randomInstance = context.getProviderStrategy().getInstance(new InstanceProvider() { - @Override - public List> getInstances() throws Exception { - return instances; - } - }); + ServiceInstance randomInstance = context.getProviderStrategy().getInstance(() -> instances); if (randomInstance == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(randomInstance).build(); } catch (Exception e) { ThreadUtils.checkInterrupted(e); - log.error(String.format("Trying to get any instance from service (%s)", name), e); + log.error("Trying to get any instance from service ({})", name, e); return Response.serverError().build(); } } @@ -204,7 +197,7 @@ private Response internalGet(String name, String id, boolean addDeprecationHeade return builder.build(); } catch (Exception e) { ThreadUtils.checkInterrupted(e); - log.error(String.format("Trying to get instance (%s) from service (%s)", id, name), e); + log.error("Trying to get instance ({}) from service ({})", id, name, e); return Response.serverError().build(); } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/InstanceCleanup.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/InstanceCleanup.java index 2923a9e63..b1bd622da 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/InstanceCleanup.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/InstanceCleanup.java @@ -61,16 +61,7 @@ public InstanceCleanup(ServiceDiscovery discovery, int instanceRefreshMs) { public void start() { Preconditions.checkArgument(!service.isShutdown(), "already started"); - service.scheduleWithFixedDelay( - new Runnable() { - @Override - public void run() { - doWork(); - } - }, - instanceRefreshMs, - instanceRefreshMs, - TimeUnit.MILLISECONDS); + service.scheduleWithFixedDelay(this::doWork, instanceRefreshMs, instanceRefreshMs, TimeUnit.MILLISECONDS); } @Override @@ -102,7 +93,7 @@ private void checkService(String name) { } } catch (Exception e) { ThreadUtils.checkInterrupted(e); - log.error(String.format("GC for service: %s", name), e); + log.error("GC for service: {}", name, e); } } }