浏览代码

ZOOKEEPER-3517: Turn on BookKeeper checkstyle configuration at project level

Turn on BookKeeper checkstyle configuration at project level.

In zookeeper-contrib we still use checkstyle-simple because there are lots of conflicts which is not worth to fix.

Author: tison <wander4096@gmail.com>

Reviewers: Enrico Olivelli <eolivelli@apache.org>, Norbert Kalmar <nkalmar@apache.org>

Closes #1060 from TisonKun/ZOOKEEPER-3517
tison 5 年之前
父节点
当前提交
b8d5d9c1c1
共有 19 个文件被更改,包括 1027 次插入1100 次删除
  1. 0 0
      checkstyle-simple.xml
  2. 2 1
      pom.xml
  3. 33 1
      zookeeper-contrib/pom.xml
  4. 1 32
      zookeeper-jute/pom.xml
  5. 1 38
      zookeeper-metrics-providers/pom.xml
  6. 10 9
      zookeeper-recipes/zookeeper-recipes-election/src/main/java/org/apache/zookeeper/recipes/leader/LeaderElectionAware.java
  7. 339 337
      zookeeper-recipes/zookeeper-recipes-election/src/main/java/org/apache/zookeeper/recipes/leader/LeaderElectionSupport.java
  8. 57 53
      zookeeper-recipes/zookeeper-recipes-election/src/main/java/org/apache/zookeeper/recipes/leader/LeaderOffer.java
  9. 192 220
      zookeeper-recipes/zookeeper-recipes-election/src/test/java/org/apache/zookeeper/recipes/leader/LeaderElectionSupportTest.java
  10. 11 8
      zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/LockListener.java
  11. 51 42
      zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/ProtocolSupport.java
  12. 80 69
      zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/WriteLock.java
  13. 19 13
      zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/ZNodeName.java
  14. 8 6
      zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/ZooKeeperOperation.java
  15. 26 26
      zookeeper-recipes/zookeeper-recipes-lock/src/test/java/org/apache/zookeeper/recipes/lock/WriteLockTest.java
  16. 27 16
      zookeeper-recipes/zookeeper-recipes-lock/src/test/java/org/apache/zookeeper/recipes/lock/ZNodeNameTest.java
  17. 75 86
      zookeeper-recipes/zookeeper-recipes-queue/src/main/java/org/apache/zookeeper/recipes/queue/DistributedQueue.java
  18. 95 111
      zookeeper-recipes/zookeeper-recipes-queue/src/test/java/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java
  19. 0 32
      zookeeper-server/pom.xml

+ 0 - 0
checkstyle.xml → checkstyle-simple.xml


+ 2 - 1
pom.xml

@@ -588,12 +588,13 @@
             </dependency>
           </dependencies>
           <configuration>
-            <configLocation>checkstyle.xml</configLocation>
+            <configLocation>checkstyle-strict.xml</configLocation>
             <suppressionsLocation>checkstyleSuppressions.xml</suppressionsLocation>
             <encoding>UTF-8</encoding>
             <consoleOutput>true</consoleOutput>
             <failOnViolation>true</failOnViolation>
             <includeResources>false</includeResources>
+            <includeTestResources>false</includeTestResources>
             <includeTestSourceDirectory>true</includeTestSourceDirectory>
           </configuration>
           <executions>

+ 33 - 1
zookeeper-contrib/pom.xml

@@ -63,8 +63,40 @@
              </compilerArgs>
             </configuration>
         </plugin>
+
+        <plugin>
+          <groupId>org.apache.maven.plugins</groupId>
+          <artifactId>maven-checkstyle-plugin</artifactId>
+          <version>3.1.0</version>
+          <dependencies>
+            <dependency>
+              <groupId>com.puppycrawl.tools</groupId>
+              <artifactId>checkstyle</artifactId>
+              <version>${checkstyle.version}</version>
+            </dependency>
+          </dependencies>
+          <configuration>
+            <configLocation>checkstyle-simple.xml</configLocation>
+            <suppressionsLocation>checkstyleSuppressions.xml</suppressionsLocation>
+            <encoding>UTF-8</encoding>
+            <consoleOutput>true</consoleOutput>
+            <failOnViolation>true</failOnViolation>
+            <includeResources>false</includeResources>
+            <includeTestSourceDirectory>true</includeTestSourceDirectory>
+            <includeTestResources>false</includeTestResources>
+          </configuration>
+          <executions>
+            <execution>
+              <id>checkstyle</id>
+              <phase>validate</phase>
+              <goals>
+                <goal>check</goal>
+              </goals>
+            </execution>
+          </executions>
+        </plugin>
       </plugins>
     </pluginManagement>
   </build>
 
-</project>
+</project>

+ 1 - 32
zookeeper-jute/pom.xml

@@ -153,38 +153,7 @@
             <skip>true</skip>
         </configuration>
       </plugin>
-
-      <plugin>
-        <groupId>org.apache.maven.plugins</groupId>
-        <artifactId>maven-checkstyle-plugin</artifactId>
-        <version>3.1.0</version>
-        <dependencies>
-          <dependency>
-            <groupId>com.puppycrawl.tools</groupId>
-            <artifactId>checkstyle</artifactId>
-            <version>${checkstyle.version}</version>
-          </dependency>
-        </dependencies>
-        <configuration>
-          <configLocation>checkstyle-strict.xml</configLocation>
-          <suppressionsLocation>checkstyleSuppressions.xml</suppressionsLocation>
-          <encoding>UTF-8</encoding>
-          <consoleOutput>true</consoleOutput>
-          <failOnViolation>true</failOnViolation>
-          <includeResources>false</includeResources>
-          <includeTestSourceDirectory>true</includeTestSourceDirectory>
-        </configuration>
-        <executions>
-          <execution>
-            <id>checkstyle</id>
-            <phase>validate</phase>
-            <goals>
-              <goal>check</goal>
-            </goals>
-          </execution>
-        </executions>
-      </plugin>
     </plugins>
   </build>
 
-</project>
+</project>

+ 1 - 38
zookeeper-metrics-providers/pom.xml

@@ -32,46 +32,9 @@
   <packaging>pom</packaging>
   <name>Apache ZooKeeper - Metrics Providers</name>
   <description>ZooKeeper Metrics Providers</description>
-  
+
   <modules>
     <module>zookeeper-prometheus-metrics</module>
   </modules>
 
-  <build>
-    <pluginManagement>
-      <plugins>
-        <plugin>
-          <groupId>org.apache.maven.plugins</groupId>
-          <artifactId>maven-checkstyle-plugin</artifactId>
-          <version>3.1.0</version>
-          <dependencies>
-            <dependency>
-              <groupId>com.puppycrawl.tools</groupId>
-              <artifactId>checkstyle</artifactId>
-              <version>${checkstyle.version}</version>
-            </dependency>
-          </dependencies>
-          <configuration>
-            <configLocation>checkstyle-strict.xml</configLocation>
-            <suppressionsLocation>checkstyleSuppressions.xml</suppressionsLocation>
-            <encoding>UTF-8</encoding>
-            <consoleOutput>true</consoleOutput>
-            <failOnViolation>true</failOnViolation>
-            <includeResources>false</includeResources>
-            <includeTestSourceDirectory>true</includeTestSourceDirectory>
-          </configuration>
-          <executions>
-            <execution>
-              <id>checkstyle</id>
-              <phase>validate</phase>
-              <goals>
-                <goal>check</goal>
-              </goals>
-            </execution>
-          </executions>
-        </plugin>
-      </plugins>
-    </pluginManagement>
-  </build>
-
 </project>

+ 10 - 9
zookeeper-recipes/zookeeper-recipes-election/src/main/java/org/apache/zookeeper/recipes/leader/LeaderElectionAware.java

@@ -14,6 +14,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.leader;
 
 import org.apache.zookeeper.recipes.leader.LeaderElectionSupport.EventType;
@@ -24,14 +25,14 @@ import org.apache.zookeeper.recipes.leader.LeaderElectionSupport.EventType;
  */
 public interface LeaderElectionAware {
 
-  /**
-   * Called during each state transition. Current, low level events are provided
-   * at the beginning and end of each state. For instance, START may be followed
-   * by OFFER_START, OFFER_COMPLETE, DETERMINE_START, DETERMINE_COMPLETE, and so
-   * on.
-   * 
-   * @param eventType
-   */
-  public void onElectionEvent(EventType eventType);
+    /**
+     * Called during each state transition. Current, low level events are provided
+     * at the beginning and end of each state. For instance, START may be followed
+     * by OFFER_START, OFFER_COMPLETE, DETERMINE_START, DETERMINE_COMPLETE, and so
+     * on.
+     *
+     * @param eventType
+     */
+    void onElectionEvent(EventType eventType);
 
 }

+ 339 - 337
zookeeper-recipes/zookeeper-recipes-election/src/main/java/org/apache/zookeeper/recipes/leader/LeaderElectionSupport.java

@@ -14,6 +14,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.leader;
 
 import java.util.ArrayList;
@@ -21,7 +22,6 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.WatchedEvent;
@@ -33,11 +33,9 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * <p>
  * A leader election support library implementing the ZooKeeper election recipe.
- * </p>
- * <p>
- * This support library is meant to simplify the construction of an exclusive
+ *
+ * <p>This support library is meant to simplify the construction of an exclusive
  * leader system on top of Apache ZooKeeper. Any application that can become the
  * leader (usually a process that provides a service, exclusively) would
  * configure an instance of this class with their hostname, at least one
@@ -47,12 +45,10 @@ import org.slf4j.LoggerFactory;
  * ZooKeeper and create a leader offer. The library then determines if it has
  * been elected the leader using the algorithm described below. The client
  * application can follow all state transitions via the listener callback.
- * </p>
- * <p>
- * Leader election algorithm
- * </p>
- * <p>
- * The library starts in a START state. Through each state transition, a state
+ *
+ * <p>Leader election algorithm
+ *
+ * <p>The library starts in a START state. Through each state transition, a state
  * start and a state complete event are sent to all listeners. When
  * {@link #start()} is called, a leader offer is created in ZooKeeper. A leader
  * offer is an ephemeral sequential node that indicates a process that can act
@@ -66,12 +62,10 @@ import org.slf4j.LoggerFactory;
  * process again to see if it should become the leader. Note that sequence ID
  * may not be contiguous due to failed processes. A process may revoke its offer
  * to be the leader at any time by calling {@link #stop()}.
- * </p>
- * <p>
- * Guarantees (not) Made and Caveats
- * </p>
- * <p>
- * <ul>
+ *
+ * <p>Guarantees (not) Made and Caveats
+ *
+ * <p><ul>
  * <li>It is possible for a (poorly implemented) process to create a leader
  * offer, get the lowest sequence ID, but have something terrible occur where it
  * maintains its connection to ZK (and thus its ephemeral leader offer node) but
@@ -94,376 +88,384 @@ import org.slf4j.LoggerFactory;
  */
 public class LeaderElectionSupport implements Watcher {
 
-  private static final Logger logger = LoggerFactory
-      .getLogger(LeaderElectionSupport.class);
-
-  private ZooKeeper zooKeeper;
-
-  private State state;
-  private Set<LeaderElectionAware> listeners;
-
-  private String rootNodeName;
-  private LeaderOffer leaderOffer;
-  private String hostName;
-
-  public LeaderElectionSupport() {
-    state = State.STOP;
-    listeners = Collections.synchronizedSet(new HashSet<LeaderElectionAware>());
-  }
-
-  /**
-   * <p>
-   * Start the election process. This method will create a leader offer,
-   * determine its status, and either become the leader or become ready. If an
-   * instance of {@link ZooKeeper} has not yet been configured by the user, a
-   * new instance is created using the connectString and sessionTime specified.
-   * </p>
-   * <p>
-   * Any (anticipated) failures result in a failed event being sent to all
-   * listeners.
-   * </p>
-   */
-  public synchronized void start() {
-    state = State.START;
-    dispatchEvent(EventType.START);
-
-    logger.info("Starting leader election support");
-
-    if (zooKeeper == null) {
-      throw new IllegalStateException(
-          "No instance of zookeeper provided. Hint: use setZooKeeper()");
+    private static final Logger LOG = LoggerFactory.getLogger(LeaderElectionSupport.class);
+
+    private ZooKeeper zooKeeper;
+
+    private State state;
+    private Set<LeaderElectionAware> listeners;
+
+    private String rootNodeName;
+    private LeaderOffer leaderOffer;
+    private String hostName;
+
+    public LeaderElectionSupport() {
+        state = State.STOP;
+        listeners = Collections.synchronizedSet(new HashSet<>());
     }
 
-    if (hostName == null) {
-      throw new IllegalStateException(
-          "No hostname provided. Hint: use setHostName()");
+    /**
+     * <p>
+     * Start the election process. This method will create a leader offer,
+     * determine its status, and either become the leader or become ready. If an
+     * instance of {@link ZooKeeper} has not yet been configured by the user, a
+     * new instance is created using the connectString and sessionTime specified.
+     * </p>
+     * <p>
+     * Any (anticipated) failures result in a failed event being sent to all
+     * listeners.
+     * </p>
+     */
+    public synchronized void start() {
+        state = State.START;
+        dispatchEvent(EventType.START);
+
+        LOG.info("Starting leader election support");
+
+        if (zooKeeper == null) {
+            throw new IllegalStateException(
+                "No instance of zookeeper provided. Hint: use setZooKeeper()");
+        }
+
+        if (hostName == null) {
+            throw new IllegalStateException(
+                "No hostname provided. Hint: use setHostName()");
+        }
+
+        try {
+            makeOffer();
+            determineElectionStatus();
+        } catch (KeeperException | InterruptedException e) {
+            becomeFailed(e);
+        }
     }
 
-    try {
-      makeOffer();
-      determineElectionStatus();
-    } catch (KeeperException e) {
-      becomeFailed(e);
-      return;
-    } catch (InterruptedException e) {
-      becomeFailed(e);
-      return;
+    /**
+     * Stops all election services, revokes any outstanding leader offers, and
+     * disconnects from ZooKeeper.
+     */
+    public synchronized void stop() {
+        state = State.STOP;
+        dispatchEvent(EventType.STOP_START);
+
+        LOG.info("Stopping leader election support");
+
+        if (leaderOffer != null) {
+            try {
+                zooKeeper.delete(leaderOffer.getNodePath(), -1);
+                LOG.info("Removed leader offer {}", leaderOffer.getNodePath());
+            } catch (InterruptedException | KeeperException e) {
+                becomeFailed(e);
+            }
+        }
+
+        dispatchEvent(EventType.STOP_COMPLETE);
     }
-  }
-
-  /**
-   * Stops all election services, revokes any outstanding leader offers, and
-   * disconnects from ZooKeeper.
-   */
-  public synchronized void stop() {
-    state = State.STOP;
-    dispatchEvent(EventType.STOP_START);
-
-    logger.info("Stopping leader election support");
-
-    if (leaderOffer != null) {
-      try {
-        zooKeeper.delete(leaderOffer.getNodePath(), -1);
-        logger.info("Removed leader offer {}", leaderOffer.getNodePath());
-      } catch (InterruptedException e) {
-        becomeFailed(e);
-      } catch (KeeperException e) {
-        becomeFailed(e);
-      }
+
+    private void makeOffer() throws KeeperException, InterruptedException {
+        state = State.OFFER;
+        dispatchEvent(EventType.OFFER_START);
+
+        LeaderOffer newLeaderOffer = new LeaderOffer();
+        byte[] hostnameBytes;
+        synchronized (this) {
+            newLeaderOffer.setHostName(hostName);
+            hostnameBytes = hostName.getBytes();
+            newLeaderOffer.setNodePath(zooKeeper.create(rootNodeName + "/" + "n_",
+                                                        hostnameBytes, ZooDefs.Ids.OPEN_ACL_UNSAFE,
+                                                        CreateMode.EPHEMERAL_SEQUENTIAL));
+            leaderOffer = newLeaderOffer;
+        }
+        LOG.debug("Created leader offer {}", leaderOffer);
+
+        dispatchEvent(EventType.OFFER_COMPLETE);
     }
 
-    dispatchEvent(EventType.STOP_COMPLETE);
-  }
-
-  private void makeOffer() throws KeeperException, InterruptedException {
-    state = State.OFFER;
-    dispatchEvent(EventType.OFFER_START);
-
-    LeaderOffer newLeaderOffer = new LeaderOffer();
-    byte[] hostnameBytes;
-    synchronized (this) {
-        newLeaderOffer.setHostName(hostName);
-        hostnameBytes = hostName.getBytes();
-        newLeaderOffer.setNodePath(zooKeeper.create(rootNodeName + "/" + "n_",
-        hostnameBytes, ZooDefs.Ids.OPEN_ACL_UNSAFE,
-        CreateMode.EPHEMERAL_SEQUENTIAL));
-        leaderOffer = newLeaderOffer;
+    private synchronized LeaderOffer getLeaderOffer() {
+        return leaderOffer;
     }
-    logger.debug("Created leader offer {}", leaderOffer);
 
-    dispatchEvent(EventType.OFFER_COMPLETE);
-  }
+    private void determineElectionStatus() throws KeeperException, InterruptedException {
 
-  private synchronized LeaderOffer getLeaderOffer() {
-      return leaderOffer;
-  }
+        state = State.DETERMINE;
+        dispatchEvent(EventType.DETERMINE_START);
 
-  private void determineElectionStatus() throws KeeperException,
-      InterruptedException {
+        LeaderOffer currentLeaderOffer = getLeaderOffer();
 
-    state = State.DETERMINE;
-    dispatchEvent(EventType.DETERMINE_START);
+        String[] components = currentLeaderOffer.getNodePath().split("/");
 
-    LeaderOffer currentLeaderOffer = getLeaderOffer();
+        currentLeaderOffer.setId(Integer.valueOf(components[components.length - 1].substring("n_".length())));
 
-    String[] components = currentLeaderOffer.getNodePath().split("/");
+        List<LeaderOffer> leaderOffers = toLeaderOffers(zooKeeper.getChildren(rootNodeName, false));
 
-    currentLeaderOffer.setId(Integer.valueOf(components[components.length - 1]
-        .substring("n_".length())));
+        /*
+         * For each leader offer, find out where we fit in. If we're first, we
+         * become the leader. If we're not elected the leader, attempt to stat the
+         * offer just less than us. If they exist, watch for their failure, but if
+         * they don't, become the leader.
+         */
+        for (int i = 0; i < leaderOffers.size(); i++) {
+            LeaderOffer leaderOffer = leaderOffers.get(i);
 
-    List<LeaderOffer> leaderOffers = toLeaderOffers(zooKeeper.getChildren(
-        rootNodeName, false));
+            if (leaderOffer.getId().equals(currentLeaderOffer.getId())) {
+                LOG.debug("There are {} leader offers. I am {} in line.", leaderOffers.size(), i);
 
-    /*
-     * For each leader offer, find out where we fit in. If we're first, we
-     * become the leader. If we're not elected the leader, attempt to stat the
-     * offer just less than us. If they exist, watch for their failure, but if
-     * they don't, become the leader.
-     */
-    for (int i = 0; i < leaderOffers.size(); i++) {
-      LeaderOffer leaderOffer = leaderOffers.get(i);
+                dispatchEvent(EventType.DETERMINE_COMPLETE);
 
-      if (leaderOffer.getId().equals(currentLeaderOffer.getId())) {
-        logger.debug("There are {} leader offers. I am {} in line.",
-            leaderOffers.size(), i);
+                if (i == 0) {
+                    becomeLeader();
+                } else {
+                    becomeReady(leaderOffers.get(i - 1));
+                }
 
-        dispatchEvent(EventType.DETERMINE_COMPLETE);
+                /* Once we've figured out where we are, we're done. */
+                break;
+            }
+        }
+    }
 
-        if (i == 0) {
-          becomeLeader();
+    private void becomeReady(LeaderOffer neighborLeaderOffer)
+        throws KeeperException, InterruptedException {
+
+        LOG.info(
+            "{} not elected leader. Watching node:{}",
+            getLeaderOffer().getNodePath(),
+            neighborLeaderOffer.getNodePath());
+
+        /*
+         * Make sure to pass an explicit Watcher because we could be sharing this
+         * zooKeeper instance with someone else.
+         */
+        Stat stat = zooKeeper.exists(neighborLeaderOffer.getNodePath(), this);
+
+        if (stat != null) {
+            dispatchEvent(EventType.READY_START);
+            LOG.debug(
+                "We're behind {} in line and they're alive. Keeping an eye on them.",
+                neighborLeaderOffer.getNodePath());
+            state = State.READY;
+            dispatchEvent(EventType.READY_COMPLETE);
         } else {
-          becomeReady(leaderOffers.get(i - 1));
+            /*
+             * If the stat fails, the node has gone missing between the call to
+             * getChildren() and exists(). We need to try and become the leader.
+             */
+            LOG.info(
+                "We were behind {} but it looks like they died. Back to determination.",
+                neighborLeaderOffer.getNodePath());
+            determineElectionStatus();
         }
 
-        /* Once we've figured out where we are, we're done. */
-        break;
-      }
     }
-  }
 
-  private void becomeReady(LeaderOffer neighborLeaderOffer)
-      throws KeeperException, InterruptedException {
+    private void becomeLeader() {
+        state = State.ELECTED;
+        dispatchEvent(EventType.ELECTED_START);
+
+        LOG.info("Becoming leader with node:{}", getLeaderOffer().getNodePath());
+
+        dispatchEvent(EventType.ELECTED_COMPLETE);
+    }
+
+    private void becomeFailed(Exception e) {
+        LOG.error("Failed in state {} - Exception:{}", state, e);
 
-    logger.info("{} not elected leader. Watching node:{}",
-        getLeaderOffer().getNodePath(), neighborLeaderOffer.getNodePath());
+        state = State.FAILED;
+        dispatchEvent(EventType.FAILED);
+    }
 
-    /*
-     * Make sure to pass an explicit Watcher because we could be sharing this
-     * zooKeeper instance with someone else.
+    /**
+     * Fetch the (user supplied) hostname of the current leader. Note that by the
+     * time this method returns, state could have changed so do not depend on this
+     * to be strongly consistent. This method has to read all leader offers from
+     * ZooKeeper to deterime who the leader is (i.e. there is no caching) so
+     * consider the performance implications of frequent invocation. If there are
+     * no leader offers this method returns null.
+     *
+     * @return hostname of the current leader
+     * @throws KeeperException
+     * @throws InterruptedException
      */
-    Stat stat = zooKeeper.exists(neighborLeaderOffer.getNodePath(), this);
-
-    if (stat != null) {
-      dispatchEvent(EventType.READY_START);
-      logger.debug(
-          "We're behind {} in line and they're alive. Keeping an eye on them.",
-          neighborLeaderOffer.getNodePath());
-      state = State.READY;
-      dispatchEvent(EventType.READY_COMPLETE);
-    } else {
-      /*
-       * If the stat fails, the node has gone missing between the call to
-       * getChildren() and exists(). We need to try and become the leader.
-       */
-      logger
-          .info(
-              "We were behind {} but it looks like they died. Back to determination.",
-              neighborLeaderOffer.getNodePath());
-      determineElectionStatus();
+    public String getLeaderHostName() throws KeeperException, InterruptedException {
+
+        List<LeaderOffer> leaderOffers = toLeaderOffers(zooKeeper.getChildren(rootNodeName, false));
+
+        if (leaderOffers.size() > 0) {
+            return leaderOffers.get(0).getHostName();
+        }
+
+        return null;
     }
 
-  }
+    private List<LeaderOffer> toLeaderOffers(List<String> strings)
+        throws KeeperException, InterruptedException {
+
+        List<LeaderOffer> leaderOffers = new ArrayList<>(strings.size());
+
+        /*
+         * Turn each child of rootNodeName into a leader offer. This is a tuple of
+         * the sequence number and the node name.
+         */
+        for (String offer : strings) {
+            String hostName = new String(zooKeeper.getData(rootNodeName + "/" + offer, false, null));
 
-  private void becomeLeader() {
-    state = State.ELECTED;
-    dispatchEvent(EventType.ELECTED_START);
+            leaderOffers.add(new LeaderOffer(
+                Integer.valueOf(offer.substring("n_".length())),
+                rootNodeName + "/" + offer, hostName));
+        }
 
-    logger.info("Becoming leader with node:{}", getLeaderOffer().getNodePath());
+        /*
+         * We sort leader offers by sequence number (which may not be zero-based or
+         * contiguous) and keep their paths handy for setting watches.
+         */
+        Collections.sort(leaderOffers, new LeaderOffer.IdComparator());
 
-    dispatchEvent(EventType.ELECTED_COMPLETE);
-  }
+        return leaderOffers;
+    }
 
-  private void becomeFailed(Exception e) {
-    logger.error("Failed in state {} - Exception:{}", state, e);
+    @Override
+    public void process(WatchedEvent event) {
+        if (event.getType().equals(Watcher.Event.EventType.NodeDeleted)) {
+            if (!event.getPath().equals(getLeaderOffer().getNodePath())
+                && state != State.STOP) {
+                LOG.debug(
+                    "Node {} deleted. Need to run through the election process.",
+                    event.getPath());
+                try {
+                    determineElectionStatus();
+                } catch (KeeperException | InterruptedException e) {
+                    becomeFailed(e);
+                }
+            }
+        }
+    }
 
-    state = State.FAILED;
-    dispatchEvent(EventType.FAILED);
-  }
+    private void dispatchEvent(EventType eventType) {
+        LOG.debug("Dispatching event:{}", eventType);
 
-  /**
-   * Fetch the (user supplied) hostname of the current leader. Note that by the
-   * time this method returns, state could have changed so do not depend on this
-   * to be strongly consistent. This method has to read all leader offers from
-   * ZooKeeper to deterime who the leader is (i.e. there is no caching) so
-   * consider the performance implications of frequent invocation. If there are
-   * no leader offers this method returns null.
-   * 
-   * @return hostname of the current leader
-   * @throws KeeperException
-   * @throws InterruptedException
-   */
-  public String getLeaderHostName() throws KeeperException,
-      InterruptedException {
+        synchronized (listeners) {
+            if (listeners.size() > 0) {
+                for (LeaderElectionAware observer : listeners) {
+                    observer.onElectionEvent(eventType);
+                }
+            }
+        }
+    }
 
-    List<LeaderOffer> leaderOffers = toLeaderOffers(zooKeeper.getChildren(
-        rootNodeName, false));
+    /**
+     * Adds {@code listener} to the list of listeners who will receive events.
+     *
+     * @param listener
+     */
+    public void addListener(LeaderElectionAware listener) {
+        listeners.add(listener);
+    }
 
-    if (leaderOffers.size() > 0) {
-      return leaderOffers.get(0).getHostName();
+    /**
+     * Remove {@code listener} from the list of listeners who receive events.
+     *
+     * @param listener
+     */
+    public void removeListener(LeaderElectionAware listener) {
+        listeners.remove(listener);
     }
 
-    return null;
-  }
+    @Override
+    public String toString() {
+        return "{"
+            + " state:" + state
+            + " leaderOffer:" + getLeaderOffer()
+            + " zooKeeper:" + zooKeeper
+            + " hostName:" + getHostName()
+            + " listeners:" + listeners
+            + " }";
+    }
 
-  private List<LeaderOffer> toLeaderOffers(List<String> strings)
-      throws KeeperException, InterruptedException {
+    /**
+     * <p>
+     * Gets the ZooKeeper root node to use for this service.
+     * </p>
+     * <p>
+     * For instance, a root node of {@code /mycompany/myservice} would be the
+     * parent of all leader offers for this service. Obviously all processes that
+     * wish to contend for leader status need to use the same root node. Note: We
+     * assume this node already exists.
+     * </p>
+     *
+     * @return a znode path
+     */
+    public String getRootNodeName() {
+        return rootNodeName;
+    }
 
-    List<LeaderOffer> leaderOffers = new ArrayList<LeaderOffer>(strings.size());
+    /**
+     * <p>
+     * Sets the ZooKeeper root node to use for this service.
+     * </p>
+     * <p>
+     * For instance, a root node of {@code /mycompany/myservice} would be the
+     * parent of all leader offers for this service. Obviously all processes that
+     * wish to contend for leader status need to use the same root node. Note: We
+     * assume this node already exists.
+     * </p>
+     */
+    public void setRootNodeName(String rootNodeName) {
+        this.rootNodeName = rootNodeName;
+    }
 
-    /*
-     * Turn each child of rootNodeName into a leader offer. This is a tuple of
-     * the sequence number and the node name.
+    /**
+     * The {@link ZooKeeper} instance to use for all operations. Provided this
+     * overrides any connectString or sessionTimeout set.
      */
-    for (String offer : strings) {
-      String hostName = new String(zooKeeper.getData(
-          rootNodeName + "/" + offer, false, null));
+    public ZooKeeper getZooKeeper() {
+        return zooKeeper;
+    }
 
-      leaderOffers.add(new LeaderOffer(Integer.valueOf(offer.substring("n_"
-          .length())), rootNodeName + "/" + offer, hostName));
+    public void setZooKeeper(ZooKeeper zooKeeper) {
+        this.zooKeeper = zooKeeper;
     }
 
-    /*
-     * We sort leader offers by sequence number (which may not be zero-based or
-     * contiguous) and keep their paths handy for setting watches.
+    /**
+     * The hostname of this process. Mostly used as a convenience for logging and
+     * to respond to {@link #getLeaderHostName()} requests.
      */
-    Collections.sort(leaderOffers, new LeaderOffer.IdComparator());
-
-    return leaderOffers;
-  }
-
-  @Override
-  public void process(WatchedEvent event) {
-    if (event.getType().equals(Watcher.Event.EventType.NodeDeleted)) {
-      if (!event.getPath().equals(getLeaderOffer().getNodePath())
-          && state != State.STOP) {
-        logger.debug(
-            "Node {} deleted. Need to run through the election process.",
-            event.getPath());
-        try {
-          determineElectionStatus();
-        } catch (KeeperException e) {
-          becomeFailed(e);
-        } catch (InterruptedException e) {
-          becomeFailed(e);
-        }
-      }
+    public synchronized String getHostName() {
+        return hostName;
     }
-  }
 
-  private void dispatchEvent(EventType eventType) {
-    logger.debug("Dispatching event:{}", eventType);
+    public synchronized void setHostName(String hostName) {
+        this.hostName = hostName;
+    }
 
-    synchronized (listeners) {
-      if (listeners.size() > 0) {
-        for (LeaderElectionAware observer : listeners) {
-          observer.onElectionEvent(eventType);
-        }
-      }
+    /**
+     * The type of event.
+     */
+    public enum EventType {
+        START,
+        OFFER_START,
+        OFFER_COMPLETE,
+        DETERMINE_START,
+        DETERMINE_COMPLETE,
+        ELECTED_START,
+        ELECTED_COMPLETE,
+        READY_START,
+        READY_COMPLETE,
+        FAILED,
+        STOP_START,
+        STOP_COMPLETE,
     }
-  }
-
-  /**
-   * Adds {@code listener} to the list of listeners who will receive events.
-   * 
-   * @param listener
-   */
-  public void addListener(LeaderElectionAware listener) {
-    listeners.add(listener);
-  }
-
-  /**
-   * Remove {@code listener} from the list of listeners who receive events.
-   * 
-   * @param listener
-   */
-  public void removeListener(LeaderElectionAware listener) {
-    listeners.remove(listener);
-  }
-
-  @Override
-  public String toString() {
-    return "{ state:" + state + " leaderOffer:" + getLeaderOffer() + " zooKeeper:"
-        + zooKeeper + " hostName:" + getHostName() + " listeners:" + listeners
-        + " }";
-  }
-
-  /**
-   * <p>
-   * Gets the ZooKeeper root node to use for this service.
-   * </p>
-   * <p>
-   * For instance, a root node of {@code /mycompany/myservice} would be the
-   * parent of all leader offers for this service. Obviously all processes that
-   * wish to contend for leader status need to use the same root node. Note: We
-   * assume this node already exists.
-   * </p>
-   * 
-   * @return a znode path
-   */
-  public String getRootNodeName() {
-    return rootNodeName;
-  }
-
-  /**
-   * <p>
-   * Sets the ZooKeeper root node to use for this service.
-   * </p>
-   * <p>
-   * For instance, a root node of {@code /mycompany/myservice} would be the
-   * parent of all leader offers for this service. Obviously all processes that
-   * wish to contend for leader status need to use the same root node. Note: We
-   * assume this node already exists.
-   * </p>
-   */
-  public void setRootNodeName(String rootNodeName) {
-    this.rootNodeName = rootNodeName;
-  }
-
-  /**
-   * The {@link ZooKeeper} instance to use for all operations. Provided this
-   * overrides any connectString or sessionTimeout set.
-   */
-  public ZooKeeper getZooKeeper() {
-    return zooKeeper;
-  }
-
-  public void setZooKeeper(ZooKeeper zooKeeper) {
-    this.zooKeeper = zooKeeper;
-  }
-
-  /**
-   * The hostname of this process. Mostly used as a convenience for logging and
-   * to respond to {@link #getLeaderHostName()} requests.
-   */
-  public synchronized String getHostName() {
-    return hostName;
-  }
-
-  public synchronized void setHostName(String hostName) {
-    this.hostName = hostName;
-  }
-
-  /**
-   * The type of event.
-   */
-  public static enum EventType {
-    START, OFFER_START, OFFER_COMPLETE, DETERMINE_START, DETERMINE_COMPLETE, ELECTED_START, ELECTED_COMPLETE, READY_START, READY_COMPLETE, FAILED, STOP_START, STOP_COMPLETE,
-  }
-
-  /**
-   * The internal state of the election support service.
-   */
-  public static enum State {
-    START, OFFER, DETERMINE, ELECTED, READY, FAILED, STOP
-  }
+
+    /**
+     * The internal state of the election support service.
+     */
+    public enum State {
+        START,
+        OFFER,
+        DETERMINE,
+        ELECTED,
+        READY,
+        FAILED,
+        STOP
+    }
+
 }

+ 57 - 53
zookeeper-recipes/zookeeper-recipes-election/src/main/java/org/apache/zookeeper/recipes/leader/LeaderOffer.java

@@ -14,6 +14,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.leader;
 
 import java.io.Serializable;
@@ -25,62 +26,65 @@ import java.util.Comparator;
  */
 public class LeaderOffer {
 
-  private Integer id;
-  private String nodePath;
-  private String hostName;
-
-  public LeaderOffer() {
-    // Default constructor
-  }
-
-  public LeaderOffer(Integer id, String nodePath, String hostName) {
-    this.id = id;
-    this.nodePath = nodePath;
-    this.hostName = hostName;
-  }
-
-  @Override
-  public String toString() {
-    return "{ id:" + id + " nodePath:" + nodePath + " hostName:" + hostName
-        + " }";
-  }
-
-  public Integer getId() {
-    return id;
-  }
-
-  public void setId(Integer id) {
-    this.id = id;
-  }
-
-  public String getNodePath() {
-    return nodePath;
-  }
-
-  public void setNodePath(String nodePath) {
-    this.nodePath = nodePath;
-  }
-
-  public String getHostName() {
-    return hostName;
-  }
-
-  public void setHostName(String hostName) {
-    this.hostName = hostName;
-  }
-
-  /**
-   * Compare two instances of {@link LeaderOffer} using only the {code}id{code}
-   * member.
-   */
-  public static class IdComparator
-          implements Comparator<LeaderOffer>, Serializable {
+    private Integer id;
+    private String nodePath;
+    private String hostName;
+
+    public LeaderOffer() {
+        // Default constructor
+    }
+
+    public LeaderOffer(Integer id, String nodePath, String hostName) {
+        this.id = id;
+        this.nodePath = nodePath;
+        this.hostName = hostName;
+    }
 
     @Override
-    public int compare(LeaderOffer o1, LeaderOffer o2) {
-      return o1.getId().compareTo(o2.getId());
+    public String toString() {
+        return "{"
+            + " id:" + id
+            + " nodePath:" + nodePath
+            + " hostName:" + hostName
+            + " }";
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getNodePath() {
+        return nodePath;
+    }
+
+    public void setNodePath(String nodePath) {
+        this.nodePath = nodePath;
+    }
+
+    public String getHostName() {
+        return hostName;
     }
 
-  }
+    public void setHostName(String hostName) {
+        this.hostName = hostName;
+    }
+
+    /**
+     * Compare two instances of {@link LeaderOffer} using only the {code}id{code}
+     * member.
+     */
+    public static class IdComparator
+        implements Comparator<LeaderOffer>, Serializable {
+
+        @Override
+        public int compare(LeaderOffer o1, LeaderOffer o2) {
+            return o1.getId().compareTo(o2.getId());
+        }
+
+    }
 
 }

+ 192 - 220
zookeeper-recipes/zookeeper-recipes-election/src/test/java/org/apache/zookeeper/recipes/leader/LeaderElectionSupportTest.java

@@ -14,18 +14,15 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.leader;
 
-import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
-
-
 import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.recipes.leader.LeaderElectionSupport.EventType;
@@ -37,262 +34,237 @@ import org.junit.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+/**
+ * Test for {@link LeaderElectionSupport}.
+ */
 public class LeaderElectionSupportTest extends ClientBase {
 
-  private static final Logger logger = LoggerFactory
-      .getLogger(LeaderElectionSupportTest.class);
-  private static final String testRootNode = "/" + System.currentTimeMillis()
-      + "_";
-
-  private ZooKeeper zooKeeper;
+    private static final Logger LOGGER = LoggerFactory.getLogger(LeaderElectionSupportTest.class);
+    private static final String TEST_ROOT_NODE = "/" + System.currentTimeMillis() + "_";
 
-  @Before
-  public void setUp() throws Exception {
-    super.setUp();
+    private ZooKeeper zooKeeper;
 
-    zooKeeper = createClient();
+    @Before
+    public void setUp() throws Exception {
+        super.setUp();
 
-    zooKeeper.create(testRootNode + Thread.currentThread().getId(),
-        new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-  }
+        zooKeeper = createClient();
 
-  @After
-  public void tearDown() throws Exception {
-    if (zooKeeper != null) {
-      zooKeeper.delete(testRootNode + Thread.currentThread().getId(), -1);
+        zooKeeper.create(
+            TEST_ROOT_NODE + Thread.currentThread().getId(),
+            new byte[0],
+            ZooDefs.Ids.OPEN_ACL_UNSAFE,
+            CreateMode.PERSISTENT);
     }
 
-    super.tearDown();
-  }
-
-  @Test
-  public void testNode() throws IOException, InterruptedException,
-      KeeperException {
+    @After
+    public void tearDown() throws Exception {
+        if (zooKeeper != null) {
+            zooKeeper.delete(TEST_ROOT_NODE + Thread.currentThread().getId(), -1);
+        }
 
-    LeaderElectionSupport electionSupport = createLeaderElectionSupport();
+        super.tearDown();
+    }
 
-    electionSupport.start();
-    Thread.sleep(3000);
-    electionSupport.stop();
-  }
+    @Test
+    public void testNode() throws Exception {
+        LeaderElectionSupport electionSupport = createLeaderElectionSupport();
 
-  @Test
-  public void testNodes3() throws IOException, InterruptedException,
-      KeeperException {
+        electionSupport.start();
+        Thread.sleep(3000);
+        electionSupport.stop();
+    }
 
-    int testIterations = 3;
-    final CountDownLatch latch = new CountDownLatch(testIterations);
-    final AtomicInteger failureCounter = new AtomicInteger();
+    @Test
+    public void testNodes3() throws Exception {
+        int testIterations = 3;
+        final CountDownLatch latch = new CountDownLatch(testIterations);
+        final AtomicInteger failureCounter = new AtomicInteger();
 
-    for (int i = 0; i < testIterations; i++) {
-      runElectionSupportThread(latch, failureCounter);
-    }
+        for (int i = 0; i < testIterations; i++) {
+            runElectionSupportThread(latch, failureCounter);
+        }
 
-    Assert.assertEquals(0, failureCounter.get());
+        Assert.assertEquals(0, failureCounter.get());
 
-    if (!latch.await(10, TimeUnit.SECONDS)) {
-      logger
-          .info(
-              "Waited for all threads to start, but timed out. We had {} failures.",
-              failureCounter);
+        if (!latch.await(10, TimeUnit.SECONDS)) {
+            LOGGER.info("Waited for all threads to start, but timed out. We had {} failures.", failureCounter);
+        }
     }
-  }
 
-  @Test
-  public void testNodes9() throws IOException, InterruptedException,
-      KeeperException {
+    @Test
+    public void testNodes9() throws Exception {
+        int testIterations = 9;
+        final CountDownLatch latch = new CountDownLatch(testIterations);
+        final AtomicInteger failureCounter = new AtomicInteger();
+
+        for (int i = 0; i < testIterations; i++) {
+            runElectionSupportThread(latch, failureCounter);
+        }
 
-    int testIterations = 9;
-    final CountDownLatch latch = new CountDownLatch(testIterations);
-    final AtomicInteger failureCounter = new AtomicInteger();
+        Assert.assertEquals(0, failureCounter.get());
 
-    for (int i = 0; i < testIterations; i++) {
-      runElectionSupportThread(latch, failureCounter);
+        if (!latch.await(10, TimeUnit.SECONDS)) {
+            LOGGER.info("Waited for all threads to start, but timed out. We had {} failures.", failureCounter);
+        }
     }
 
-    Assert.assertEquals(0, failureCounter.get());
+    @Test
+    public void testNodes20() throws Exception {
+        int testIterations = 20;
+        final CountDownLatch latch = new CountDownLatch(testIterations);
+        final AtomicInteger failureCounter = new AtomicInteger();
+
+        for (int i = 0; i < testIterations; i++) {
+            runElectionSupportThread(latch, failureCounter);
+        }
 
-    if (!latch.await(10, TimeUnit.SECONDS)) {
-      logger
-          .info(
-              "Waited for all threads to start, but timed out. We had {} failures.",
-              failureCounter);
+        Assert.assertEquals(0, failureCounter.get());
+
+        if (!latch.await(10, TimeUnit.SECONDS)) {
+            LOGGER.info("Waited for all threads to start, but timed out. We had {} failures.", failureCounter);
+        }
     }
-  }
 
-  @Test
-  public void testNodes20() throws IOException, InterruptedException,
-      KeeperException {
+    @Test
+    public void testNodes100() throws Exception {
+        int testIterations = 100;
+        final CountDownLatch latch = new CountDownLatch(testIterations);
+        final AtomicInteger failureCounter = new AtomicInteger();
+
+        for (int i = 0; i < testIterations; i++) {
+            runElectionSupportThread(latch, failureCounter);
+        }
 
-    int testIterations = 20;
-    final CountDownLatch latch = new CountDownLatch(testIterations);
-    final AtomicInteger failureCounter = new AtomicInteger();
+        Assert.assertEquals(0, failureCounter.get());
 
-    for (int i = 0; i < testIterations; i++) {
-      runElectionSupportThread(latch, failureCounter);
+        if (!latch.await(20, TimeUnit.SECONDS)) {
+            LOGGER.info("Waited for all threads to start, but timed out. We had {} failures.", failureCounter);
+        }
     }
 
-    Assert.assertEquals(0, failureCounter.get());
+    @Test
+    public void testOfferShuffle() throws InterruptedException {
+        int testIterations = 10;
+        final CountDownLatch latch = new CountDownLatch(testIterations);
+        final AtomicInteger failureCounter = new AtomicInteger();
+        List<Thread> threads = new ArrayList<>(testIterations);
+
+        for (int i = 1; i <= testIterations; i++) {
+            threads.add(runElectionSupportThread(latch, failureCounter, Math.min(i * 1200, 10000)));
+        }
 
-    if (!latch.await(10, TimeUnit.SECONDS)) {
-      logger
-          .info(
-              "Waited for all threads to start, but timed out. We had {} failures.",
-              failureCounter);
+        if (!latch.await(60, TimeUnit.SECONDS)) {
+            LOGGER.info("Waited for all threads to start, but timed out. We had {} failures.", failureCounter);
+        }
     }
-  }
 
-  @Test
-  public void testNodes100() throws IOException, InterruptedException,
-      KeeperException {
+    @Test
+    public void testGetLeaderHostName() throws Exception {
+        LeaderElectionSupport electionSupport = createLeaderElectionSupport();
 
-    int testIterations = 100;
-    final CountDownLatch latch = new CountDownLatch(testIterations);
-    final AtomicInteger failureCounter = new AtomicInteger();
+        electionSupport.start();
 
-    for (int i = 0; i < testIterations; i++) {
-      runElectionSupportThread(latch, failureCounter);
-    }
+        // Sketchy: We assume there will be a leader (probably us) in 3 seconds.
+        Thread.sleep(3000);
+
+        String leaderHostName = electionSupport.getLeaderHostName();
 
-    Assert.assertEquals(0, failureCounter.get());
+        Assert.assertNotNull(leaderHostName);
+        Assert.assertEquals("foohost", leaderHostName);
 
-    if (!latch.await(20, TimeUnit.SECONDS)) {
-      logger
-          .info(
-              "Waited for all threads to start, but timed out. We had {} failures.",
-              failureCounter);
+        electionSupport.stop();
     }
-  }
-
-  @Test
-  public void testOfferShuffle() throws InterruptedException {
-    int testIterations = 10;
-    final CountDownLatch latch = new CountDownLatch(testIterations);
-    final AtomicInteger failureCounter = new AtomicInteger();
-    List<Thread> threads = new ArrayList<Thread>(testIterations);
-
-    for (int i = 1; i <= testIterations; i++) {
-      threads.add(runElectionSupportThread(latch, failureCounter,
-          Math.min(i * 1200, 10000)));
+
+    @Test
+    public void testReadyOffer() throws Exception {
+        final ArrayList<EventType> events = new ArrayList<>();
+        final CountDownLatch electedComplete = new CountDownLatch(1);
+
+        final LeaderElectionSupport electionSupport1 = createLeaderElectionSupport();
+        electionSupport1.start();
+        LeaderElectionSupport electionSupport2 = createLeaderElectionSupport();
+        LeaderElectionAware listener = new LeaderElectionAware() {
+            boolean stoppedElectedNode = false;
+            @Override
+            public void onElectionEvent(EventType eventType) {
+                events.add(eventType);
+                if (!stoppedElectedNode
+                    && eventType == EventType.DETERMINE_COMPLETE) {
+                    stoppedElectedNode = true;
+                    try {
+                        // stopping the ELECTED node, so re-election will happen.
+                        electionSupport1.stop();
+                    } catch (Exception e) {
+                        LOGGER.error("Unexpected error", e);
+                    }
+                }
+                if (eventType == EventType.ELECTED_COMPLETE) {
+                    electedComplete.countDown();
+                }
+            }
+        };
+        electionSupport2.addListener(listener);
+        electionSupport2.start();
+        // waiting for re-election.
+        electedComplete.await(CONNECTION_TIMEOUT / 3, TimeUnit.MILLISECONDS);
+
+        final ArrayList<EventType> expectedevents = new ArrayList<>();
+        expectedevents.add(EventType.START);
+        expectedevents.add(EventType.OFFER_START);
+        expectedevents.add(EventType.OFFER_COMPLETE);
+        expectedevents.add(EventType.DETERMINE_START);
+        expectedevents.add(EventType.DETERMINE_COMPLETE);
+        expectedevents.add(EventType.DETERMINE_START);
+        expectedevents.add(EventType.DETERMINE_COMPLETE);
+        expectedevents.add(EventType.ELECTED_START);
+        expectedevents.add(EventType.ELECTED_COMPLETE);
+
+        Assert.assertEquals("Events has failed to executed in the order", expectedevents, events);
+
+        electionSupport2.stop();
     }
 
-    if (!latch.await(60, TimeUnit.SECONDS)) {
-      logger
-          .info(
-              "Waited for all threads to start, but timed out. We had {} failures.",
-              failureCounter);
+    private LeaderElectionSupport createLeaderElectionSupport() {
+        LeaderElectionSupport electionSupport = new LeaderElectionSupport();
+
+        electionSupport.setZooKeeper(zooKeeper);
+        electionSupport.setRootNodeName(TEST_ROOT_NODE + Thread.currentThread().getId());
+        electionSupport.setHostName("foohost");
+
+        return electionSupport;
     }
-  }
-
-  @Test
-  public void testGetLeaderHostName() throws KeeperException,
-      InterruptedException {
-
-    LeaderElectionSupport electionSupport = createLeaderElectionSupport();
-
-    electionSupport.start();
-
-    // Sketchy: We assume there will be a leader (probably us) in 3 seconds.
-    Thread.sleep(3000);
-
-    String leaderHostName = electionSupport.getLeaderHostName();
-
-    Assert.assertNotNull(leaderHostName);
-    Assert.assertEquals("foohost", leaderHostName);
-
-    electionSupport.stop();
-  }
-
-  @Test
-  public void testReadyOffer() throws Exception {
-      final ArrayList<EventType> events = new ArrayList<EventType>();
-      final CountDownLatch electedComplete = new CountDownLatch(1);
-
-      final LeaderElectionSupport electionSupport1 = createLeaderElectionSupport();
-      electionSupport1.start();
-      LeaderElectionSupport electionSupport2 = createLeaderElectionSupport();
-      LeaderElectionAware listener = new LeaderElectionAware() {
-          boolean stoppedElectedNode = false;
-          @Override
-          public void onElectionEvent(EventType eventType) {
-              events.add(eventType);
-              if (!stoppedElectedNode
-                      && eventType == EventType.DETERMINE_COMPLETE) {
-                  stoppedElectedNode = true;
-                  try {
-                      // stopping the ELECTED node, so re-election will happen.
-                      electionSupport1.stop();
-                  } catch (Exception e) {
-                      logger.error("Unexpected error", e);
-                  }
-              }
-              if (eventType == EventType.ELECTED_COMPLETE) {
-                  electedComplete.countDown();
-              }
-          }
-      };
-      electionSupport2.addListener(listener);
-      electionSupport2.start();
-      // waiting for re-election.
-      electedComplete.await(CONNECTION_TIMEOUT / 3, TimeUnit.MILLISECONDS);
-
-      final ArrayList<EventType> expectedevents = new ArrayList<EventType>();
-      expectedevents.add(EventType.START);
-      expectedevents.add(EventType.OFFER_START);
-      expectedevents.add(EventType.OFFER_COMPLETE);
-      expectedevents.add(EventType.DETERMINE_START);
-      expectedevents.add(EventType.DETERMINE_COMPLETE);
-      expectedevents.add(EventType.DETERMINE_START);
-      expectedevents.add(EventType.DETERMINE_COMPLETE);
-      expectedevents.add(EventType.ELECTED_START);
-      expectedevents.add(EventType.ELECTED_COMPLETE);
-      Assert.assertEquals("Events has failed to executed in the order",
-              expectedevents, events);
-      electionSupport2.stop();
-  }
-  
-  private LeaderElectionSupport createLeaderElectionSupport() {
-    LeaderElectionSupport electionSupport = new LeaderElectionSupport();
-
-    electionSupport.setZooKeeper(zooKeeper);
-    electionSupport.setRootNodeName(testRootNode
-        + Thread.currentThread().getId());
-    electionSupport.setHostName("foohost");
-
-    return electionSupport;
-  }
-
-  private Thread runElectionSupportThread(final CountDownLatch latch,
-      final AtomicInteger failureCounter) {
-    return runElectionSupportThread(latch, failureCounter, 3000);
-  }
-
-  private Thread runElectionSupportThread(final CountDownLatch latch,
-      final AtomicInteger failureCounter, final long sleepDuration) {
-
-    final LeaderElectionSupport electionSupport = createLeaderElectionSupport();
-
-    Thread t = new Thread() {
-
-      @Override
-      public void run() {
-        try {
-          electionSupport.start();
-          Thread.sleep(sleepDuration);
-          electionSupport.stop();
-
-          latch.countDown();
-        } catch (Exception e) {
-          logger.warn("Failed to run leader election due to: {}",
-              e.getMessage());
-          failureCounter.incrementAndGet();
-        }
-      }
-    };
 
-    t.start();
+    private Thread runElectionSupportThread(
+        final CountDownLatch latch,
+        final AtomicInteger failureCounter) {
+        return runElectionSupportThread(latch, failureCounter, 3000);
+    }
 
-    return t;
-  }
+    private Thread runElectionSupportThread(
+        final CountDownLatch latch,
+        final AtomicInteger failureCounter,
+        final long sleepDuration) {
+        final LeaderElectionSupport electionSupport = createLeaderElectionSupport();
+
+        Thread t = new Thread(() -> {
+            try {
+                electionSupport.start();
+                Thread.sleep(sleepDuration);
+                electionSupport.stop();
+
+                latch.countDown();
+            } catch (Exception e) {
+                LOGGER.warn(
+                    "Failed to run leader election due to: {}",
+                    e.getMessage());
+                failureCounter.incrementAndGet();
+            }
+        });
+
+        t.start();
+
+        return t;
+    }
 
 }

+ 11 - 8
zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/LockListener.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -15,24 +15,27 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.lock;
 
 /**
  * This class has two methods which are call
- * back methods when a lock is acquired and 
+ * back methods when a lock is acquired and
  * when the lock is released.
  *
  */
 public interface LockListener {
+
     /**
-     * call back called when the lock 
-     * is acquired
+     * call back called when the lock
+     * is acquired.
      */
-    public void lockAcquired();
-    
+    void lockAcquired();
+
     /**
-     * call back called when the lock is 
+     * call back called when the lock is
      * released.
      */
-    public void lockReleased();
+    void lockReleased();
+
 }

+ 51 - 42
zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/ProtocolSupport.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -15,29 +15,28 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.lock;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.data.ACL;
 import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.recipes.lock.ZooKeeperOperation;
-
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
- * A base class for protocol implementations which provides a number of higher 
+ * A base class for protocol implementations which provides a number of higher
  * level helper methods for working with ZooKeeper along with retrying synchronous
- *  operations if the connection to ZooKeeper closes such as 
- *  {@link #retryOperation(ZooKeeperOperation)}
- *
+ *  operations if the connection to ZooKeeper closes such as
+ *  {@link #retryOperation(ZooKeeperOperation)}.
  */
 class ProtocolSupport {
+
     private static final Logger LOG = LoggerFactory.getLogger(ProtocolSupport.class);
 
     protected final ZooKeeper zookeeper;
@@ -52,16 +51,17 @@ class ProtocolSupport {
 
     /**
      * Closes this strategy and releases any ZooKeeper resources; but keeps the
-     *  ZooKeeper instance open
+     *  ZooKeeper instance open.
      */
     public void close() {
         if (closed.compareAndSet(false, true)) {
             doClose();
         }
     }
-    
+
     /**
-     * return zookeeper client instance
+     * return zookeeper client instance.
+     *
      * @return zookeeper client instance
      */
     public ZooKeeper getZookeeper() {
@@ -69,7 +69,8 @@ class ProtocolSupport {
     }
 
     /**
-     * return the acl its using
+     * return the acl its using.
+     *
      * @return the acl.
      */
     public List<ACL> getAcl() {
@@ -77,7 +78,8 @@ class ProtocolSupport {
     }
 
     /**
-     * set the acl 
+     * set the acl.
+     *
      * @param acl the acl to set to
      */
     public void setAcl(List<ACL> acl) {
@@ -85,7 +87,8 @@ class ProtocolSupport {
     }
 
     /**
-     * get the retry delay in milliseconds
+     * get the retry delay in milliseconds.
+     *
      * @return the retry delay
      */
     public long getRetryDelay() {
@@ -93,7 +96,8 @@ class ProtocolSupport {
     }
 
     /**
-     * Sets the time waited between retry delays
+     * Sets the time waited between retry delays.
+     *
      * @param retryDelay the retry delay
      */
     public void setRetryDelay(long retryDelay) {
@@ -101,19 +105,20 @@ class ProtocolSupport {
     }
 
     /**
-     * Allow derived classes to perform 
-     * some custom closing operations to release resources
+     * Allow derived classes to perform
+     * some custom closing operations to release resources.
      */
     protected void doClose() {
-    }
 
+    }
 
     /**
-     * Perform the given operation, retrying if the connection fails
-     * @return object. it needs to be cast to the callee's expected 
+     * Perform the given operation, retrying if the connection fails.
+     *
+     * @return object. it needs to be cast to the callee's expected
      * return type.
      */
-    protected Object retryOperation(ZooKeeperOperation operation) 
+    protected Object retryOperation(ZooKeeperOperation operation)
         throws KeeperException, InterruptedException {
         KeeperException exception = null;
         for (int i = 0; i < retryCount; i++) {
@@ -126,17 +131,18 @@ class ProtocolSupport {
                 if (exception == null) {
                     exception = e;
                 }
-                LOG.debug("Attempt {} failed with connection loss so " +
-                    "attempting to reconnect", i, e);
+                LOG.debug("Attempt {} failed with connection loss so attempting to reconnect", i, e);
                 retryDelay(i);
             }
         }
+
         throw exception;
     }
 
     /**
      * Ensures that the given path exists with no data, the current
-     * ACL and no flags
+     * ACL and no flags.
+     *
      * @param path
      */
     protected void ensurePathExists(String path) {
@@ -144,33 +150,34 @@ class ProtocolSupport {
     }
 
     /**
-     * Ensures that the given path exists with the given data, ACL and flags
+     * Ensures that the given path exists with the given data, ACL and flags.
+     *
      * @param path
      * @param acl
      * @param flags
      */
-    protected void ensureExists(final String path, final byte[] data,
-            final List<ACL> acl, final CreateMode flags) {
+    protected void ensureExists(
+        final String path,
+        final byte[] data,
+        final List<ACL> acl,
+        final CreateMode flags) {
         try {
-            retryOperation(new ZooKeeperOperation() {
-                public boolean execute() throws KeeperException, InterruptedException {
-                    Stat stat = zookeeper.exists(path, false);
-                    if (stat != null) {
-                        return true;
-                    }
-                    zookeeper.create(path, data, acl, flags);
+            retryOperation(() -> {
+                Stat stat = zookeeper.exists(path, false);
+                if (stat != null) {
                     return true;
                 }
+                zookeeper.create(path, data, acl, flags);
+                return true;
             });
-        } catch (KeeperException e) {
-            LOG.warn("Caught: " + e, e);
-        } catch (InterruptedException e) {
+        } catch (KeeperException | InterruptedException e) {
             LOG.warn("Caught: " + e, e);
         }
     }
 
     /**
-     * Returns true if this protocol has been closed
+     * Returns true if this protocol has been closed.
+     *
      * @return true if this protocol is closed
      */
     protected boolean isClosed() {
@@ -178,7 +185,8 @@ class ProtocolSupport {
     }
 
     /**
-     * Performs a retry delay if this is not the first attempt
+     * Performs a retry delay if this is not the first attempt.
+     *
      * @param attemptCount the number of the attempts performed so far
      */
     protected void retryDelay(int attemptCount) {
@@ -190,4 +198,5 @@ class ProtocolSupport {
             }
         }
     }
+
 }

+ 80 - 69
zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/WriteLock.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -15,33 +15,36 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.lock;
 
+import static org.apache.zookeeper.CreateMode.EPHEMERAL_SEQUENTIAL;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.util.List;
+import java.util.SortedSet;
+import java.util.TreeSet;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.WatchedEvent;
 import org.apache.zookeeper.Watcher;
-import static org.apache.zookeeper.CreateMode.EPHEMERAL_SEQUENTIAL;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.data.ACL;
 import org.apache.zookeeper.data.Stat;
-
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * A <a href="package.html">protocol to implement an exclusive
- *  write lock or to elect a leader</a>. <p> You invoke {@link #lock()} to 
- *  start the process of grabbing the lock; you may get the lock then or it may be 
- *  some time later. <p> You can register a listener so that you are invoked 
- *  when you get the lock; otherwise you can ask if you have the lock
- *  by calling {@link #isOwner()}
+ *  write lock or to elect a leader</a>.
+ *
+ *  <p>You invoke {@link #lock()} to start the process of grabbing the lock;
+ *  you may get the lock then or it may be some time later.
+ *
+ *  <p>You can register a listener so that you are invoked when you get the lock;
+ *  otherwise you can ask if you have the lock by calling {@link #isOwner()}.
  *
  */
 public class WriteLock extends ProtocolSupport {
+
     private static final Logger LOG = LoggerFactory.getLogger(WriteLock.class);
 
     private final String dir;
@@ -52,13 +55,13 @@ public class WriteLock extends ProtocolSupport {
     private byte[] data = {0x12, 0x34};
     private LockListener callback;
     private LockZooKeeperOperation zop;
-    
+
     /**
-     * zookeeper contructor for writelock
+     * zookeeper contructor for writelock.
+     *
      * @param zookeeper zookeeper client instance
      * @param dir the parent path you want to use for locking
-     * @param acl the acls that you want to use for all the paths,
-     * if null world read/write is used.
+     * @param acl the acls that you want to use for all the paths, if null world read/write is used.
      */
     public WriteLock(ZooKeeper zookeeper, String dir, List<ACL> acl) {
         super(zookeeper);
@@ -68,30 +71,36 @@ public class WriteLock extends ProtocolSupport {
         }
         this.zop = new LockZooKeeperOperation();
     }
-    
+
     /**
-     * zookeeper contructor for writelock with callback
+     * zookeeper contructor for writelock with callback.
+     *
      * @param zookeeper the zookeeper client instance
      * @param dir the parent path you want to use for locking
      * @param acl the acls that you want to use for all the paths
      * @param callback the call back instance
      */
-    public WriteLock(ZooKeeper zookeeper, String dir, List<ACL> acl, 
-            LockListener callback) {
+    public WriteLock(
+        ZooKeeper zookeeper,
+        String dir,
+        List<ACL> acl,
+        LockListener callback) {
         this(zookeeper, dir, acl);
         this.callback = callback;
     }
 
     /**
-     * return the current locklistener
+     * return the current locklistener.
+     *
      * @return the locklistener
      */
     public synchronized LockListener getLockListener() {
         return this.callback;
     }
-    
+
     /**
-     * register a different call back listener
+     * register a different call back listener.
+     *
      * @param callback the call back instance
      */
     public synchronized void setLockListener(LockListener callback) {
@@ -99,41 +108,37 @@ public class WriteLock extends ProtocolSupport {
     }
 
     /**
-     * Removes the lock or associated znode if 
-     * you no longer require the lock. this also 
+     * Removes the lock or associated znode if
+     * you no longer require the lock. this also
      * removes your request in the queue for locking
      * in case you do not already hold the lock.
+     *
      * @throws RuntimeException throws a runtime exception
      * if it cannot connect to zookeeper.
      */
     public synchronized void unlock() throws RuntimeException {
-        
+
         if (!isClosed() && id != null) {
             // we don't need to retry this operation in the case of failure
             // as ZK will remove ephemeral files and we don't wanna hang
             // this process when closing if we cannot reconnect to ZK
             try {
-                
-                ZooKeeperOperation zopdel = new ZooKeeperOperation() {
-                    public boolean execute() throws KeeperException,
-                        InterruptedException {
-                        zookeeper.delete(id, -1);   
-                        return Boolean.TRUE;
-                    }
+
+                ZooKeeperOperation zopdel = () -> {
+                    zookeeper.delete(id, -1);
+                    return Boolean.TRUE;
                 };
                 zopdel.execute();
             } catch (InterruptedException e) {
                 LOG.warn("Caught: " + e, e);
                 //set that we have been interrupted.
-               Thread.currentThread().interrupt();
+                Thread.currentThread().interrupt();
             } catch (KeeperException.NoNodeException e) {
                 // do nothing
             } catch (KeeperException e) {
                 LOG.warn("Caught: " + e, e);
-                throw (RuntimeException) new RuntimeException(e.getMessage()).
-                    initCause(e);
-            }
-            finally {
+                throw new RuntimeException(e.getMessage(), e);
+            } finally {
                 LockListener lockListener = getLockListener();
                 if (lockListener != null) {
                     lockListener.lockReleased();
@@ -142,13 +147,14 @@ public class WriteLock extends ProtocolSupport {
             }
         }
     }
-    
-    /** 
-     * the watcher called on  
-     * getting watch while watching 
-     * my predecessor
+
+    /**
+     * the watcher called on
+     * getting watch while watching
+     * my predecessor.
      */
     private class LockWatcher implements Watcher {
+
         public void process(WatchedEvent event) {
             // lets either become the leader or watch the new/updated node
             LOG.debug("Watcher fired: {}", event);
@@ -158,23 +164,25 @@ public class WriteLock extends ProtocolSupport {
                 LOG.warn("Failed to acquire lock: " + e, e);
             }
         }
+
     }
-    
+
     /**
      * a zoookeeper operation that is mainly responsible
      * for all the magic required for locking.
      */
-    private  class LockZooKeeperOperation implements ZooKeeperOperation {
-        
-        /** find if we have been created earler if not create our node
-         * 
+    private class LockZooKeeperOperation implements ZooKeeperOperation {
+
+        /**
+         * find if we have been created earler if not create our node.
+         *
          * @param prefix the prefix node
          * @param zookeeper teh zookeeper client
          * @param dir the dir paretn
          * @throws KeeperException
          * @throws InterruptedException
          */
-        private void findPrefixInChildren(String prefix, ZooKeeper zookeeper, String dir) 
+        private void findPrefixInChildren(String prefix, ZooKeeper zookeeper, String dir)
             throws KeeperException, InterruptedException {
             List<String> names = zookeeper.getChildren(dir, false);
             for (String name : names) {
@@ -185,40 +193,40 @@ public class WriteLock extends ProtocolSupport {
                 }
             }
             if (id == null) {
-                id = zookeeper.create(dir + "/" + prefix, data, 
-                        getAcl(), EPHEMERAL_SEQUENTIAL);
+                id = zookeeper.create(dir + "/" + prefix, data, getAcl(), EPHEMERAL_SEQUENTIAL);
 
                 LOG.debug("Created id: {}", id);
             }
 
         }
-        
+
         /**
-         * the command that is run and retried for actually 
-         * obtaining the lock
+         * the command that is run and retried for actually
+         * obtaining the lock.
+         *
          * @return if the command was successful or not
          */
-        @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF_NONVIRTUAL",
-                justification = "findPrefixInChildren will assign a value to this.id")
+        @SuppressFBWarnings(
+            value = "NP_NULL_PARAM_DEREF_NONVIRTUAL",
+            justification = "findPrefixInChildren will assign a value to this.id")
         public boolean execute() throws KeeperException, InterruptedException {
             do {
                 if (id == null) {
                     long sessionId = zookeeper.getSessionId();
                     String prefix = "x-" + sessionId + "-";
-                    // lets try look up the current ID if we failed 
+                    // lets try look up the current ID if we failed
                     // in the middle of creating the znode
                     findPrefixInChildren(prefix, zookeeper, dir);
                     idName = new ZNodeName(id);
                 }
                 List<String> names = zookeeper.getChildren(dir, false);
                 if (names.isEmpty()) {
-                    LOG.warn("No children in: " + dir + " when we've just " +
-                    "created one! Lets recreate it...");
+                    LOG.warn("No children in: " + dir + " when we've just created one! Lets recreate it...");
                     // lets force the recreation of the id
                     id = null;
                 } else {
                     // lets sort them explicitly (though they do seem to come back in order ususally :)
-                    SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
+                    SortedSet<ZNodeName> sortedNames = new TreeSet<>();
                     for (String name : names) {
                         sortedNames.add(new ZNodeName(dir + "/" + name));
                     }
@@ -232,8 +240,7 @@ public class WriteLock extends ProtocolSupport {
                         if (stat != null) {
                             return Boolean.FALSE;
                         } else {
-                            LOG.warn("Could not find the" +
-                                            " stats for less than me: " + lastChildName.getName());
+                            LOG.warn("Could not find the stats for less than me: " + lastChildName.getName());
                         }
                     } else {
                         if (isOwner()) {
@@ -249,7 +256,8 @@ public class WriteLock extends ProtocolSupport {
             while (id == null);
             return Boolean.FALSE;
         }
-    };
+
+    }
 
     /**
      * Attempts to acquire the exclusive write lock returning whether or not it was
@@ -266,7 +274,8 @@ public class WriteLock extends ProtocolSupport {
     }
 
     /**
-     * return the parent dir for lock
+     * return the parent dir for lock.
+     *
      * @return the parent dir used for locks.
      */
     public String getDir() {
@@ -275,18 +284,20 @@ public class WriteLock extends ProtocolSupport {
 
     /**
      * Returns true if this node is the owner of the
-     *  lock (or the leader)
+     *  lock (or the leader).
      */
     public boolean isOwner() {
-        return id != null && ownerId != null && id.equals(ownerId);
+        return id != null && id.equals(ownerId);
     }
 
     /**
-     * return the id for this lock
+     * return the id for this lock.
+     *
      * @return the id for this lock
      */
     public String getId() {
-       return this.id;
+        return this.id;
     }
+
 }
 

+ 19 - 13
zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/ZNodeName.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.lock;
 
 import org.slf4j.Logger;
@@ -22,15 +23,16 @@ import org.slf4j.LoggerFactory;
 
 /**
  * Represents an ephemeral znode name which has an ordered sequence number
- * and can be sorted in order
+ * and can be sorted in order.
  *
  */
 class ZNodeName implements Comparable<ZNodeName> {
+
     private final String name;
     private String prefix;
     private int sequence = -1;
     private static final Logger LOG = LoggerFactory.getLogger(ZNodeName.class);
-    
+
     public ZNodeName(String name) {
         if (name == null) {
             throw new NullPointerException("id cannot be null");
@@ -47,7 +49,7 @@ class ZNodeName implements Comparable<ZNodeName> {
             } catch (NumberFormatException e) {
                 LOG.info("Number format exception for " + idx, e);
             } catch (ArrayIndexOutOfBoundsException e) {
-               LOG.info("Array out of bounds for " + idx, e);
+                LOG.info("Array out of bounds for " + idx, e);
             }
         }
     }
@@ -59,14 +61,16 @@ class ZNodeName implements Comparable<ZNodeName> {
 
     @Override
     public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
 
         ZNodeName sequence = (ZNodeName) o;
 
-        if (!name.equals(sequence.name)) return false;
-
-        return true;
+        return name.equals(sequence.name);
     }
 
     @Override
@@ -75,7 +79,8 @@ class ZNodeName implements Comparable<ZNodeName> {
     }
 
     /**
-     * Compare znodes based on their sequence number
+     * Compare znodes based on their sequence number.
+     *
      * @param that other znode to compare to
      * @return the difference between their sequence numbers: a positive value if this
      *         znode has a larger sequence number, 0 if they have the same sequence number
@@ -90,23 +95,24 @@ class ZNodeName implements Comparable<ZNodeName> {
     }
 
     /**
-     * Returns the name of the znode
+     * Returns the name of the znode.
      */
     public String getName() {
         return name;
     }
 
     /**
-     * Returns the sequence number
+     * Returns the sequence number.
      */
     public int getZNodeName() {
         return sequence;
     }
 
     /**
-     * Returns the text prefix before the sequence number
+     * Returns the text prefix before the sequence number.
      */
     public String getPrefix() {
         return prefix;
     }
+
 }

+ 8 - 6
zookeeper-recipes/zookeeper-recipes-lock/src/main/java/org/apache/zookeeper/recipes/lock/ZooKeeperOperation.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -15,24 +15,26 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.lock;
 
 import org.apache.zookeeper.KeeperException;
 
 /**
- * A callback object which can be used for implementing retry-able operations in the 
- * {@link org.apache.zookeeper.recipes.lock.ProtocolSupport} class
+ * A callback object which can be used for implementing retry-able operations in the
+ * {@link org.apache.zookeeper.recipes.lock.ProtocolSupport} class.
  *
  */
 public interface ZooKeeperOperation {
-    
+
     /**
      * Performs the operation - which may be involved multiple times if the connection
-     * to ZooKeeper closes during this operation
+     * to ZooKeeper closes during this operation.
      *
      * @return the result of the operation or null
      * @throws KeeperException
      * @throws InterruptedException
      */
-    public boolean execute() throws KeeperException, InterruptedException;
+    boolean execute() throws KeeperException, InterruptedException;
+
 }

+ 26 - 26
zookeeper-recipes/zookeeper-recipes-lock/src/test/java/org/apache/zookeeper/recipes/lock/WriteLockTest.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -15,22 +15,22 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.apache.zookeeper.recipes.lock;
 
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.test.ClientBase;
+package org.apache.zookeeper.recipes.lock;
 
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
-
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.test.ClientBase;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Test;
 
 /**
- * test for writelock
+ * test for writelock.
  */
 public class WriteLockTest extends ClientBase {
+
     protected int sessionTimeout = 10 * 1000;
     protected String dir = "/" + getClass().getName();
     protected WriteLock[] nodes;
@@ -45,14 +45,15 @@ public class WriteLockTest extends ClientBase {
     }
 
     class LockCallback implements LockListener {
+
         public void lockAcquired() {
             latch.countDown();
         }
 
         public void lockReleased() {
-            
+
         }
-        
+
     }
     protected void runTest(int count) throws Exception {
         nodes = new WriteLock[count];
@@ -82,23 +83,22 @@ public class WriteLockTest extends ClientBase {
 
         if (count > 1) {
             if (killLeader) {
-            System.out.println("Now killing the leader");
-            // now lets kill the leader
-            latch = new CountDownLatch(1);
-            first.unlock();
-            latch.await(30, TimeUnit.SECONDS);
-            //Thread.sleep(10000);
-            WriteLock second = nodes[1];
-            dumpNodes(count);
-            // lets assert that the first election is the leader
-            Assert.assertTrue("The second znode should be the leader " + second.getId(), second.isOwner());
-
-            for (int i = 2; i < count; i++) {
-                WriteLock node = nodes[i];
-                Assert.assertFalse("Node should not be the leader " + node.getId(), node.isOwner());
-            }
-            }
+                System.out.println("Now killing the leader");
+                // now lets kill the leader
+                latch = new CountDownLatch(1);
+                first.unlock();
+                latch.await(30, TimeUnit.SECONDS);
+                //Thread.sleep(10000);
+                WriteLock second = nodes[1];
+                dumpNodes(count);
+                // lets assert that the first election is the leader
+                Assert.assertTrue("The second znode should be the leader " + second.getId(), second.isOwner());
 
+                for (int i = 2; i < count; i++) {
+                    WriteLock node = nodes[i];
+                    Assert.assertFalse("Node should not be the leader " + node.getId(), node.isOwner());
+                }
+            }
 
             if (restartServer) {
                 // now lets stop the server
@@ -126,8 +126,7 @@ public class WriteLockTest extends ClientBase {
     protected void dumpNodes(int count) {
         for (int i = 0; i < count; i++) {
             WriteLock node = nodes[i];
-            System.out.println("node: " + i + " id: " + 
-                    node.getId() + " is leader: " + node.isOwner());
+            System.out.println("node: " + i + " id: " + node.getId() + " is leader: " + node.isOwner());
         }
     }
 
@@ -153,4 +152,5 @@ public class WriteLockTest extends ClientBase {
         super.tearDown();
 
     }
+
 }

+ 27 - 16
zookeeper-recipes/zookeeper-recipes-lock/src/test/java/org/apache/zookeeper/recipes/lock/ZNodeNameTest.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -15,51 +15,62 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.apache.zookeeper.recipes.lock;
-
 
-import org.junit.Assert;
-import org.junit.Test;
+package org.apache.zookeeper.recipes.lock;
 
 import java.util.SortedSet;
 import java.util.TreeSet;
+import org.junit.Assert;
+import org.junit.Test;
 
 /**
- * test for znodenames
+ * test for znodenames.
  */
 public class ZNodeNameTest {
+
     @Test
     public void testOrderWithSamePrefix() throws Exception {
-        String[] names = { "x-3", "x-5", "x-11", "x-1" };
-        String[] expected = { "x-1", "x-3", "x-5", "x-11" };
+        String[] names = {"x-3", "x-5", "x-11", "x-1"};
+        String[] expected = {"x-1", "x-3", "x-5", "x-11"};
         assertOrderedNodeNames(names, expected);
     }
     @Test
     public void testOrderWithDifferentPrefixes() throws Exception {
-        String[] names = { "r-3", "r-2", "r-1", "w-2", "w-1" };
-        String[] expected = { "r-1", "w-1", "r-2", "w-2", "r-3" };
+        String[] names = {"r-3", "r-2", "r-1", "w-2", "w-1"};
+        String[] expected = {"r-1", "w-1", "r-2", "w-2", "r-3"};
         assertOrderedNodeNames(names, expected);
     }
     @Test
     public void testOrderWithDifferentPrefixIncludingSessionId() throws Exception {
-        String[] names = { "x-242681582799028564-0000000002", "x-170623981976748329-0000000003", "x-98566387950223723-0000000001" };
-        String[] expected = { "x-98566387950223723-0000000001", "x-242681582799028564-0000000002", "x-170623981976748329-0000000003" };
+        String[] names = {
+            "x-242681582799028564-0000000002",
+            "x-170623981976748329-0000000003",
+            "x-98566387950223723-0000000001"
+        };
+        String[] expected = {
+            "x-98566387950223723-0000000001",
+            "x-242681582799028564-0000000002",
+            "x-170623981976748329-0000000003"
+        };
         assertOrderedNodeNames(names, expected);
     }
     @Test
     public void testOrderWithExtraPrefixes() throws Exception {
-        String[] names = { "r-1-3-2", "r-2-2-1", "r-3-1-3" };
-        String[] expected = { "r-2-2-1", "r-1-3-2", "r-3-1-3" };
+        String[] names = {"r-1-3-2", "r-2-2-1", "r-3-1-3"};
+        String[] expected = {"r-2-2-1", "r-1-3-2", "r-3-1-3"};
         assertOrderedNodeNames(names, expected);
     }
 
     protected void assertOrderedNodeNames(String[] names, String[] expected) {
         int size = names.length;
-        SortedSet<ZNodeName> nodeNames = new TreeSet<ZNodeName>();
+        SortedSet<ZNodeName> nodeNames = new TreeSet<>();
         for (String name : names) {
             nodeNames.add(new ZNodeName(name));
         }
-        Assert.assertEquals("The SortedSet does not have the expected size!", nodeNames.size(), expected.length);
+        Assert.assertEquals(
+            "The SortedSet does not have the expected size!",
+            nodeNames.size(),
+            expected.length);
 
         int index = 0;
         for (ZNodeName nodeName : nodeNames) {

+ 75 - 86
zookeeper-recipes/zookeeper-recipes-queue/src/main/java/org/apache/zookeeper/recipes/queue/DistributedQueue.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -23,9 +23,6 @@ import java.util.Map;
 import java.util.NoSuchElementException;
 import java.util.TreeMap;
 import java.util.concurrent.CountDownLatch;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.WatchedEvent;
@@ -33,15 +30,14 @@ import org.apache.zookeeper.Watcher;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.data.ACL;
-import org.apache.zookeeper.data.Stat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
- * 
  * A <a href="package.html">protocol to implement a distributed queue</a>.
- * 
  */
-
 public class DistributedQueue {
+
     private static final Logger LOG = LoggerFactory.getLogger(DistributedQueue.class);
 
     private final String dir;
@@ -51,46 +47,39 @@ public class DistributedQueue {
 
     private final String prefix = "qn-";
 
-
-    public DistributedQueue(ZooKeeper zookeeper, String dir, List<ACL> acl){
+    public DistributedQueue(ZooKeeper zookeeper, String dir, List<ACL> acl) {
         this.dir = dir;
 
-        if(acl != null){
+        if (acl != null) {
             this.acl = acl;
         }
         this.zookeeper = zookeeper;
 
     }
 
-
-
     /**
      * Returns a Map of the children, ordered by id.
      * @param watcher optional watcher on getChildren() operation.
      * @return map from id to child name for all children
      */
-    private Map<Long,String> orderedChildren(Watcher watcher) throws KeeperException, InterruptedException {
-        Map<Long,String> orderedChildren = new TreeMap<Long,String>();
-
-        List<String> childNames = null;
-        try{
-            childNames = zookeeper.getChildren(dir, watcher);
-        }catch (KeeperException.NoNodeException e){
-            throw e;
-        }
+    private Map<Long, String> orderedChildren(Watcher watcher) throws KeeperException, InterruptedException {
+        Map<Long, String> orderedChildren = new TreeMap<>();
 
-        for(String childName : childNames){
-            try{
+        List<String> childNames;
+        childNames = zookeeper.getChildren(dir, watcher);
+
+        for (String childName : childNames) {
+            try {
                 //Check format
-                if(!childName.regionMatches(0, prefix, 0, prefix.length())){
+                if (!childName.regionMatches(0, prefix, 0, prefix.length())) {
                     LOG.warn("Found child node with improper name: " + childName);
                     continue;
                 }
                 String suffix = childName.substring(prefix.length());
                 Long childId = Long.parseLong(suffix);
-                orderedChildren.put(childId,childName);
-            }catch(NumberFormatException e){
-                LOG.warn("Found child node with improper format : " + childName + " " + e,e);
+                orderedChildren.put(childId, childName);
+            } catch (NumberFormatException e) {
+                LOG.warn("Found child node with improper format : " + childName + " " + e, e);
             }
         }
 
@@ -105,37 +94,36 @@ public class DistributedQueue {
         long minId = Long.MAX_VALUE;
         String minName = "";
 
-        List<String> childNames = null;
+        List<String> childNames;
 
-        try{
+        try {
             childNames = zookeeper.getChildren(dir, false);
-        }catch(KeeperException.NoNodeException e){
-            LOG.warn("Caught: " +e,e);
+        } catch (KeeperException.NoNodeException e) {
+            LOG.warn("Caught: " + e, e);
             return null;
         }
 
-        for(String childName : childNames){
-            try{
+        for (String childName : childNames) {
+            try {
                 //Check format
-                if(!childName.regionMatches(0, prefix, 0, prefix.length())){
+                if (!childName.regionMatches(0, prefix, 0, prefix.length())) {
                     LOG.warn("Found child node with improper name: " + childName);
                     continue;
                 }
                 String suffix = childName.substring(prefix.length());
                 long childId = Long.parseLong(suffix);
-                if(childId < minId){
+                if (childId < minId) {
                     minId = childId;
                     minName = childName;
                 }
-            }catch(NumberFormatException e){
-                LOG.warn("Found child node with improper format : " + childName + " " + e,e);
+            } catch (NumberFormatException e) {
+                LOG.warn("Found child node with improper format : " + childName + " " + e, e);
             }
         }
 
-
-        if(minId < Long.MAX_VALUE){
+        if (minId < Long.MAX_VALUE) {
             return minName;
-        }else{
+        } else {
             return null;
         }
     }
@@ -148,26 +136,28 @@ public class DistributedQueue {
      * @throws InterruptedException
      */
     public byte[] element() throws NoSuchElementException, KeeperException, InterruptedException {
-        Map<Long,String> orderedChildren;
+        Map<Long, String> orderedChildren;
 
         // element, take, and remove follow the same pattern.
         // We want to return the child node with the smallest sequence number.
-        // Since other clients are remove()ing and take()ing nodes concurrently, 
+        // Since other clients are remove()ing and take()ing nodes concurrently,
         // the child with the smallest sequence number in orderedChildren might be gone by the time we check.
         // We don't call getChildren again until we have tried the rest of the nodes in sequence order.
-        while(true){
-            try{
+        while (true) {
+            try {
                 orderedChildren = orderedChildren(null);
-            }catch(KeeperException.NoNodeException e){
+            } catch (KeeperException.NoNodeException e) {
+                throw new NoSuchElementException();
+            }
+            if (orderedChildren.size() == 0) {
                 throw new NoSuchElementException();
             }
-            if(orderedChildren.size() == 0 ) throw new NoSuchElementException();
 
-            for(String headNode : orderedChildren.values()){
-                if(headNode != null){
-                    try{
-                        return zookeeper.getData(dir+"/"+headNode, false, null);
-                    }catch(KeeperException.NoNodeException e){
+            for (String headNode : orderedChildren.values()) {
+                if (headNode != null) {
+                    try {
+                        return zookeeper.getData(dir + "/" + headNode, false, null);
+                    } catch (KeeperException.NoNodeException e) {
                         //Another client removed the node first, try next
                     }
                 }
@@ -176,7 +166,6 @@ public class DistributedQueue {
         }
     }
 
-
     /**
      * Attempts to remove the head of the queue and return it.
      * @return The former head of the queue
@@ -185,23 +174,25 @@ public class DistributedQueue {
      * @throws InterruptedException
      */
     public byte[] remove() throws NoSuchElementException, KeeperException, InterruptedException {
-        Map<Long,String> orderedChildren;
+        Map<Long, String> orderedChildren;
         // Same as for element.  Should refactor this.
-        while(true){
-            try{
+        while (true) {
+            try {
                 orderedChildren = orderedChildren(null);
-            }catch(KeeperException.NoNodeException e){
+            } catch (KeeperException.NoNodeException e) {
+                throw new NoSuchElementException();
+            }
+            if (orderedChildren.size() == 0) {
                 throw new NoSuchElementException();
             }
-            if(orderedChildren.size() == 0) throw new NoSuchElementException();
 
-            for(String headNode : orderedChildren.values()){
-                String path = dir +"/"+headNode;
-                try{
+            for (String headNode : orderedChildren.values()) {
+                String path = dir + "/" + headNode;
+                try {
                     byte[] data = zookeeper.getData(path, false, null);
                     zookeeper.delete(path, -1);
                     return data;
-                }catch(KeeperException.NoNodeException e){
+                } catch (KeeperException.NoNodeException e) {
                     // Another client deleted the node first.
                 }
             }
@@ -213,17 +204,18 @@ public class DistributedQueue {
 
         CountDownLatch latch;
 
-        public LatchChildWatcher(){
+        public LatchChildWatcher() {
             latch = new CountDownLatch(1);
         }
 
-        public void process(WatchedEvent event){
+        public void process(WatchedEvent event) {
             LOG.debug("Watcher fired: {}", event);
             latch.countDown();
         }
         public void await() throws InterruptedException {
             latch.await();
         }
+
     }
 
     /**
@@ -234,28 +226,28 @@ public class DistributedQueue {
      * @throws InterruptedException
      */
     public byte[] take() throws KeeperException, InterruptedException {
-        Map<Long,String> orderedChildren;
+        Map<Long, String> orderedChildren;
         // Same as for element.  Should refactor this.
-        while(true){
+        while (true) {
             LatchChildWatcher childWatcher = new LatchChildWatcher();
-            try{
+            try {
                 orderedChildren = orderedChildren(childWatcher);
-            }catch(KeeperException.NoNodeException e){
+            } catch (KeeperException.NoNodeException e) {
                 zookeeper.create(dir, new byte[0], acl, CreateMode.PERSISTENT);
                 continue;
             }
-            if(orderedChildren.size() == 0){
+            if (orderedChildren.size() == 0) {
                 childWatcher.await();
                 continue;
             }
 
-            for(String headNode : orderedChildren.values()){
-                String path = dir +"/"+headNode;
-                try{
+            for (String headNode : orderedChildren.values()) {
+                String path = dir + "/" + headNode;
+                try {
                     byte[] data = zookeeper.getData(path, false, null);
                     zookeeper.delete(path, -1);
                     return data;
-                }catch(KeeperException.NoNodeException e){
+                } catch (KeeperException.NoNodeException e) {
                     // Another client deleted the node first.
                 }
             }
@@ -267,12 +259,12 @@ public class DistributedQueue {
      * @param data
      * @return true if data was successfully added
      */
-    public boolean offer(byte[] data) throws KeeperException, InterruptedException{
-        for(;;){
-            try{
-                zookeeper.create(dir+"/"+prefix, data, acl, CreateMode.PERSISTENT_SEQUENTIAL);
+    public boolean offer(byte[] data) throws KeeperException, InterruptedException {
+        for (; ; ) {
+            try {
+                zookeeper.create(dir + "/" + prefix, data, acl, CreateMode.PERSISTENT_SEQUENTIAL);
                 return true;
-            }catch(KeeperException.NoNodeException e){
+            } catch (KeeperException.NoNodeException e) {
                 zookeeper.create(dir, new byte[0], acl, CreateMode.PERSISTENT);
             }
         }
@@ -285,15 +277,14 @@ public class DistributedQueue {
      * @throws KeeperException
      * @throws InterruptedException
      */
-    public byte[] peek() throws KeeperException, InterruptedException{
-        try{
+    public byte[] peek() throws KeeperException, InterruptedException {
+        try {
             return element();
-        }catch(NoSuchElementException e){
+        } catch (NoSuchElementException e) {
             return null;
         }
     }
 
-
     /**
      * Attempts to remove the head of the queue and return it. Returns null if the queue is empty.
      * @return Head of the queue or null.
@@ -301,13 +292,11 @@ public class DistributedQueue {
      * @throws InterruptedException
      */
     public byte[] poll() throws KeeperException, InterruptedException {
-        try{
+        try {
             return remove();
-        }catch(NoSuchElementException e){
+        } catch (NoSuchElementException e) {
             return null;
         }
     }
 
-
-
 }

+ 95 - 111
zookeeper-recipes/zookeeper-recipes-queue/src/test/java/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java

@@ -1,4 +1,4 @@
-/**
+/*
  *
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements.  See the NOTICE file distributed with
@@ -15,10 +15,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.recipes.queue;
 
 import java.util.NoSuchElementException;
-
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.test.ClientBase;
@@ -26,8 +26,9 @@ import org.junit.After;
 import org.junit.Assert;
 import org.junit.Test;
 
-
-
+/**
+ * Tests for {@link DistributedQueue}.
+ */
 public class DistributedQueueTest extends ClientBase {
 
     @After
@@ -36,15 +37,14 @@ public class DistributedQueueTest extends ClientBase {
         LOG.info("FINISHED " + getTestName());
     }
 
-
     @Test
     public void testOffer1() throws Exception {
         String dir = "/testOffer1";
         String testString = "Hello World";
-        final int num_clients = 1;
-        ZooKeeper[] clients = new ZooKeeper[num_clients];
-        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
-        for(int i=0; i < clients.length; i++){
+        final int numClients = 1;
+        ZooKeeper[] clients = new ZooKeeper[numClients];
+        DistributedQueue[] queueHandles = new DistributedQueue[numClients];
+        for (int i = 0; i < clients.length; i++) {
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
@@ -59,10 +59,10 @@ public class DistributedQueueTest extends ClientBase {
     public void testOffer2() throws Exception {
         String dir = "/testOffer2";
         String testString = "Hello World";
-        final int num_clients = 2;
-        ZooKeeper[] clients = new ZooKeeper[num_clients];
-        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
-        for(int i=0; i < clients.length; i++){
+        final int numClients = 2;
+        ZooKeeper[] clients = new ZooKeeper[numClients];
+        DistributedQueue[] queueHandles = new DistributedQueue[numClients];
+        for (int i = 0; i < clients.length; i++) {
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
@@ -77,10 +77,10 @@ public class DistributedQueueTest extends ClientBase {
     public void testTake1() throws Exception {
         String dir = "/testTake1";
         String testString = "Hello World";
-        final int num_clients = 1;
-        ZooKeeper[] clients = new ZooKeeper[num_clients];
-        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
-        for(int i=0; i < clients.length; i++){
+        final int numClients = 1;
+        ZooKeeper[] clients = new ZooKeeper[numClients];
+        DistributedQueue[] queueHandles = new DistributedQueue[numClients];
+        for (int i = 0; i < clients.length; i++) {
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
@@ -91,196 +91,180 @@ public class DistributedQueueTest extends ClientBase {
         Assert.assertEquals(new String(dequeuedBytes), testString);
     }
 
-
-
     @Test
-    public void testRemove1() throws Exception{
+    public void testRemove1() throws Exception {
         String dir = "/testRemove1";
-        String testString = "Hello World";
-        final int num_clients = 1;
-        ZooKeeper[] clients = new ZooKeeper[num_clients];
-        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
-        for(int i=0; i < clients.length; i++){
+        final int numClients = 1;
+        ZooKeeper[] clients = new ZooKeeper[numClients];
+        DistributedQueue[] queueHandles = new DistributedQueue[numClients];
+        for (int i = 0; i < clients.length; i++) {
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
 
-        try{
+        try {
             queueHandles[0].remove();
-        }catch(NoSuchElementException e){
+        } catch (NoSuchElementException e) {
             return;
         }
-        Assert.assertTrue(false);
+
+        Assert.fail();
     }
 
-    public void createNremoveMtest(String dir,int n,int m) throws Exception{
+    public void createNremoveMtest(String dir, int n, int m) throws Exception {
         String testString = "Hello World";
-        final int num_clients = 2;
-        ZooKeeper[] clients = new ZooKeeper[num_clients];
-        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
-        for(int i=0; i < clients.length; i++){
+        final int numClients = 2;
+        ZooKeeper[] clients = new ZooKeeper[numClients];
+        DistributedQueue[] queueHandles = new DistributedQueue[numClients];
+        for (int i = 0; i < clients.length; i++) {
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
 
-        for(int i=0; i< n; i++){
+        for (int i = 0; i < n; i++) {
             String offerString = testString + i;
             queueHandles[0].offer(offerString.getBytes());
         }
 
         byte[] data = null;
-        for(int i=0; i<m; i++){
-            data=queueHandles[1].remove();
+        for (int i = 0; i < m; i++) {
+            data = queueHandles[1].remove();
         }
-        Assert.assertEquals(new String(data), testString+(m-1));
+
+        Assert.assertNotNull(data);
+        Assert.assertEquals(new String(data), testString + (m - 1));
     }
 
     @Test
-    public void testRemove2() throws Exception{
-        createNremoveMtest("/testRemove2",10,2);
+    public void testRemove2() throws Exception {
+        createNremoveMtest("/testRemove2", 10, 2);
     }
     @Test
-    public void testRemove3() throws Exception{
-        createNremoveMtest("/testRemove3",1000,1000);
+    public void testRemove3() throws Exception {
+        createNremoveMtest("/testRemove3", 1000, 1000);
     }
 
-    public void createNremoveMelementTest(String dir,int n,int m) throws Exception{
+    public void createNremoveMelementTest(String dir, int n, int m) throws Exception {
         String testString = "Hello World";
-        final int num_clients = 2;
-        ZooKeeper[] clients = new ZooKeeper[num_clients];
-        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
-        for(int i=0; i < clients.length; i++){
+        final int numClients = 2;
+        ZooKeeper[] clients = new ZooKeeper[numClients];
+        DistributedQueue[] queueHandles = new DistributedQueue[numClients];
+        for (int i = 0; i < clients.length; i++) {
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
 
-        for(int i=0; i< n; i++){
+        for (int i = 0; i < n; i++) {
             String offerString = testString + i;
             queueHandles[0].offer(offerString.getBytes());
         }
 
-        byte[] data = null;
-        for(int i=0; i<m; i++){
-            data=queueHandles[1].remove();
+        for (int i = 0; i < m; i++) {
+            queueHandles[1].remove();
         }
-        Assert.assertEquals(new String(queueHandles[1].element()), testString+m);
+        Assert.assertEquals(new String(queueHandles[1].element()), testString + m);
     }
 
     @Test
     public void testElement1() throws Exception {
-        createNremoveMelementTest("/testElement1",1,0);
+        createNremoveMelementTest("/testElement1", 1, 0);
     }
 
     @Test
     public void testElement2() throws Exception {
-        createNremoveMelementTest("/testElement2",10,2);
+        createNremoveMelementTest("/testElement2", 10, 2);
     }
 
     @Test
     public void testElement3() throws Exception {
-        createNremoveMelementTest("/testElement3",1000,500);
+        createNremoveMelementTest("/testElement3", 1000, 500);
     }
 
     @Test
     public void testElement4() throws Exception {
-        createNremoveMelementTest("/testElement4",1000,1000-1);
+        createNremoveMelementTest("/testElement4", 1000, 1000 - 1);
     }
 
     @Test
-    public void testTakeWait1() throws Exception{
+    public void testTakeWait1() throws Exception {
         String dir = "/testTakeWait1";
         final String testString = "Hello World";
-        final int num_clients = 1;
-        final ZooKeeper[] clients = new ZooKeeper[num_clients];
-        final DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
-        for(int i=0; i < clients.length; i++){
+        final int numClients = 1;
+        final ZooKeeper[] clients = new ZooKeeper[numClients];
+        final DistributedQueue[] queueHandles = new DistributedQueue[numClients];
+        for (int i = 0; i < clients.length; i++) {
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
 
-        final byte[] takeResult[] = new byte[1][];
-        Thread takeThread = new Thread(){
-            public void run(){
-                try{
-                    takeResult[0] = queueHandles[0].take();
-                }catch(KeeperException e){
-
-                }catch(InterruptedException e){
-
-                }
+        final byte[][] takeResult = new byte[1][];
+        Thread takeThread = new Thread(() -> {
+            try {
+                takeResult[0] = queueHandles[0].take();
+            } catch (KeeperException | InterruptedException ignore) {
+                // no op
             }
-        };
+        });
         takeThread.start();
 
         Thread.sleep(1000);
-        Thread offerThread= new Thread() {
-            public void run(){
-                try {
-                    queueHandles[0].offer(testString.getBytes());
-                } catch (KeeperException e) {
-
-                } catch (InterruptedException e) {
-
-                }
+        Thread offerThread = new Thread(() -> {
+            try {
+                queueHandles[0].offer(testString.getBytes());
+            } catch (KeeperException | InterruptedException ignore) {
+                // no op
             }
-        };
+        });
         offerThread.start();
         offerThread.join();
 
         takeThread.join();
 
-        Assert.assertTrue(takeResult[0] != null);
+        Assert.assertNotNull(takeResult[0]);
         Assert.assertEquals(new String(takeResult[0]), testString);
     }
 
     @Test
-    public void testTakeWait2() throws Exception{
+    public void testTakeWait2() throws Exception {
         String dir = "/testTakeWait2";
         final String testString = "Hello World";
-        final int num_clients = 1;
-        final ZooKeeper[] clients = new ZooKeeper[num_clients];
-        final DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
-        for(int i=0; i < clients.length; i++){
+        final int numClients = 1;
+        final ZooKeeper[] clients = new ZooKeeper[numClients];
+        final DistributedQueue[] queueHandles = new DistributedQueue[numClients];
+        for (int i = 0; i < clients.length; i++) {
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
-        int num_attempts =2;
-        for(int i=0; i< num_attempts; i++){
-            final byte[] takeResult[] = new byte[1][];
+        int numAttempts = 2;
+        for (int i = 0; i < numAttempts; i++) {
+            final byte[][] takeResult = new byte[1][];
             final String threadTestString = testString + i;
-            Thread takeThread = new Thread(){
-                public void run(){
-                    try{
-                        takeResult[0] = queueHandles[0].take();
-                    }catch(KeeperException e){
-
-                    }catch(InterruptedException e){
-
-                    }
+            Thread takeThread = new Thread(() -> {
+                try {
+                    takeResult[0] = queueHandles[0].take();
+                } catch (KeeperException | InterruptedException ignore) {
+                    // no op
                 }
-            };
+            });
             takeThread.start();
 
             Thread.sleep(1000);
-            Thread offerThread= new Thread() {
-                public void run(){
-                    try {
-                        queueHandles[0].offer(threadTestString.getBytes());
-                    } catch (KeeperException e) {
-
-                    } catch (InterruptedException e) {
-
-                    }
+            Thread offerThread = new Thread(() -> {
+                try {
+                    queueHandles[0].offer(threadTestString.getBytes());
+                } catch (KeeperException | InterruptedException ignore) {
+                    // no op
                 }
-            };
+            });
             offerThread.start();
             offerThread.join();
 
             takeThread.join();
 
-            Assert.assertTrue(takeResult[0] != null);
+            Assert.assertNotNull(takeResult[0]);
             Assert.assertEquals(new String(takeResult[0]), threadTestString);
         }
     }
+
 }
 

+ 0 - 32
zookeeper-server/pom.xml

@@ -290,38 +290,6 @@
           </systemPropertyVariables>
         </configuration>
       </plugin>
-
-      <plugin>
-        <groupId>org.apache.maven.plugins</groupId>
-        <artifactId>maven-checkstyle-plugin</artifactId>
-        <version>3.1.0</version>
-        <dependencies>
-          <dependency>
-            <groupId>com.puppycrawl.tools</groupId>
-            <artifactId>checkstyle</artifactId>
-            <version>${checkstyle.version}</version>
-          </dependency>
-        </dependencies>
-        <configuration>
-          <configLocation>checkstyle-strict.xml</configLocation>
-          <suppressionsLocation>checkstyleSuppressions.xml</suppressionsLocation>
-          <encoding>UTF-8</encoding>
-          <consoleOutput>true</consoleOutput>
-          <failOnViolation>true</failOnViolation>
-          <includeResources>false</includeResources>
-          <includeTestSourceDirectory>true</includeTestSourceDirectory>
-          <includeTestResources>false</includeTestResources>
-        </configuration>
-        <executions>
-          <execution>
-            <id>checkstyle</id>
-            <phase>validate</phase>
-            <goals>
-              <goal>check</goal>
-            </goals>
-          </execution>
-        </executions>
-      </plugin>
     </plugins>
   </build>