helix-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From hu...@apache.org
Subject [helix] 33/44: TEST: Groom and refactor Helix integration tests
Date Sat, 25 May 2019 01:20:07 GMT
This is an automated email from the ASF dual-hosted git repository.

hulee pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git

commit 5ce3934c5b4655e90021061720adbb3a42b1bb6b
Author: Hunter Lee <hulee@linkedin.com>
AuthorDate: Fri May 3 17:52:17 2019 -0700

    TEST: Groom and refactor Helix integration tests
    
    It was observed that there was a lot of technical debt (improper and buggy cleanup) in Helix's unit and integration tests. There were also mock controller and participant threads that were never shut down properly. This was preventing mvn test suite from completing over a remote machine (TMC), and even on local environments, mvn test was not passing. This diff refactors tests and makes sure that ZK is cleaned up after tests.
    
    Changelist:
    1. Inspect and correct mock threads (controller, participant, spectator, etc)
    2. Ensure there are no leftover garbage clusters from tests
    3. Java 8 syntax
    4. Style fixes in old tests using Helix open source style file (helix-style.xml)
    
    RB=1654905
    G=helix-reviewers
    A=jxue,eblumena
    
    Signed-off-by: Hunter Lee <hulee@linkedin.com>
---
 .../org/apache/helix/ClusterMessagingService.java  |  17 +-
 .../java/org/apache/helix/task/TaskDriver.java     |   6 +-
 .../main/java/org/apache/helix/task/TaskUtil.java  |  43 ++---
 .../apache/helix/tools/ClusterStateVerifier.java   |   3 +-
 .../BestPossibleExternalViewVerifier.java          |   9 +-
 .../ClusterVerifiers/ZkHelixClusterVerifier.java   |  12 +-
 helix-core/src/test/conf/testng.xml                |   2 +-
 .../src/test/java/org/apache/helix/TestHelper.java |   8 +-
 .../apache/helix/TestHierarchicalDataStore.java    |   2 +
 .../test/java/org/apache/helix/TestZkBasis.java    |  45 ++---
 .../java/org/apache/helix/TestZnodeModify.java     |  45 +++--
 .../java/org/apache/helix/common/ZkTestBase.java   | 120 ++++++++----
 .../rebalancer/TestZeroReplicaAvoidance.java       |  74 ++++----
 .../helix/controller/stages/BaseStageTest.java     |   3 +-
 .../controller/stages/DummyClusterManager.java     |   1 -
 .../controller/stages/TestExternalViewStage.java   |  29 ++-
 .../stages/TestMessageThrottleStage.java           |  33 ++--
 .../controller/stages/TestRebalancePipeline.java   |  63 ++++---
 .../apache/helix/integration/TestAddClusterV2.java |  16 +-
 .../TestAddNodeAfterControllerStart.java           |  64 ++++---
 .../integration/TestAlertingRebalancerFailure.java |  91 ++++-----
 .../integration/TestBatchMessageHandling.java      |  58 ++++--
 .../integration/TestCMWithFailParticipant.java     |   1 +
 .../TestCorrectnessOnConnectivityLoss.java         |  10 +
 .../org/apache/helix/integration/TestDisable.java  |  75 ++++----
 .../integration/TestDisableCustomCodeRunner.java   |  79 ++++----
 .../helix/integration/TestDisableExternalView.java |   3 +-
 .../helix/integration/TestDisablePartition.java    |  39 ++--
 .../helix/integration/TestDisableResource.java     | 145 ++++++++------
 .../helix/integration/TestDistributedCMMain.java   |  10 +-
 .../TestDistributedClusterController.java          |  40 ++--
 .../org/apache/helix/integration/TestDrop.java     |  76 ++++----
 .../helix/integration/TestEnableCompression.java   |  15 +-
 .../TestEnablePartitionDuringDisable.java          |  23 +--
 .../helix/integration/TestErrorPartition.java      |  36 ++--
 .../helix/integration/TestExternalViewUpdates.java |   5 +-
 .../integration/TestHelixCustomCodeRunner.java     |  29 ++-
 .../integration/TestHelixUsingDifferentParams.java |  44 +++--
 .../integration/TestPartitionMovementThrottle.java |  86 ++++-----
 .../apache/helix/integration/TestPauseSignal.java  |  23 +--
 .../integration/TestPreferenceListAsQueue.java     | 109 +++++------
 .../TestRebalancerPersistAssignments.java          |  70 +++----
 .../TestReelectedPipelineCorrectness.java          |   2 +-
 .../helix/integration/TestRenamePartition.java     |  40 ++--
 .../helix/integration/TestResetInstance.java       |   1 +
 .../apache/helix/integration/TestSchemataSM.java   |  18 +-
 .../integration/TestSessionExpiryInTransition.java |  11 +-
 .../helix/integration/TestStandAloneCMMain.java    |  43 ++---
 .../integration/TestStandAloneCMSessionExpiry.java |  32 ++--
 .../integration/TestStateTransitionThrottle.java   |  24 +--
 .../integration/TestSyncSessionToController.java   |  45 ++++-
 .../integration/TestWeightBasedRebalanceUtil.java  |  82 ++++----
 .../helix/integration/TestZkConnectionLost.java    |  66 ++++---
 .../helix/integration/TestZkSessionExpiry.java     |  40 ++--
 .../integration/common/ZkStandAloneCMTestBase.java |   6 +-
 .../controller/TestClusterMaintenanceMode.java     |  53 +++---
 .../controller/TestControllerLeadershipChange.java |  32 ++--
 .../manager/TestConsecutiveZkSessionExpiry.java    |   3 +-
 .../integration/manager/TestControllerManager.java |   3 +-
 .../manager/TestDistributedControllerManager.java  |  59 +++---
 .../integration/manager/TestHelixDataAccessor.java |  42 ++++-
 .../manager/TestParticipantManager.java            | 102 +++++-----
 .../integration/manager/TestZkHelixAdmin.java      |  34 ++--
 .../TestCrossClusterMessagingService.java          |  65 +++----
 .../messaging/TestGroupCommitAddBackData.java      |  39 ++--
 .../messaging/TestMessageThrottle2.java            | 199 ++++++++++----------
 .../messaging/TestP2PMessageSemiAuto.java          |  95 +++++-----
 .../messaging/TestP2PNoDuplicatedMessage.java      |   4 +-
 .../messaging/TestP2PSingleTopState.java           |  18 +-
 .../messaging/TestSchedulerMessage.java            | 137 ++++++--------
 .../CrushRebalancers/TestCrushAutoRebalance.java   |  72 ++++---
 .../TestCrushAutoRebalanceNonRack.java             |  47 +++--
 .../rebalancer/CrushRebalancers/TestNodeSwap.java  |  49 ++---
 .../TestDelayedAutoRebalance.java                  |   6 +-
 .../integration/rebalancer/TestAutoRebalance.java  |  90 ++++-----
 .../TestAutoRebalancePartitionLimit.java           |  77 ++++----
 .../TestAutoRebalanceWithDisabledInstance.java     | 101 ++++------
 ...rInMaintenanceModeWhenReachingMaxPartition.java |  27 ++-
 ...nanceModeWhenReachingOfflineInstancesLimit.java |  59 +++---
 .../rebalancer/TestCustomIdealState.java           |  31 ++-
 .../rebalancer/TestSemiAutoRebalance.java          |  27 +--
 .../rebalancer/TestZeroReplicaAvoidance.java       |  74 +++++---
 .../TestRoutingTableProviderFromCurrentStates.java |  69 ++++---
 .../TestRoutingTableProviderFromTargetEV.java      |  37 ++--
 .../TestRoutingTableProviderPeriodicRefresh.java   |   3 +-
 .../spectator/TestRoutingTableSnapshot.java        |  41 +++-
 .../helix/integration/task/TestBatchAddJobs.java   |  25 ++-
 .../helix/integration/task/TestDeleteWorkflow.java |  76 +++++---
 .../helix/integration/task/TestJobFailure.java     |  53 +++---
 .../helix/integration/task/TestJobTimeout.java     | 122 +++++++-----
 .../helix/integration/task/TestNoDoubleAssign.java |  51 +++--
 .../integration/task/TestQuotaBasedScheduling.java |  28 ++-
 .../helix/integration/task/TestStopWorkflow.java   |  72 ++++---
 .../task/TestTaskAssignmentCalculator.java         |  24 +--
 .../integration/task/TestTaskConditionalRetry.java |   9 +-
 .../task/TestTaskRebalancerRetryLimit.java         |   8 +-
 .../task/TestTaskRebalancerStopResume.java         |  85 ++++-----
 .../helix/integration/task/TestTaskThrottling.java |  59 +++---
 .../apache/helix/manager/zk/TestRawZkClient.java   | 118 +++++-------
 .../manager/zk/TestWtCacheAsyncOpMultiThread.java  |  42 ++---
 .../manager/zk/TestWtCacheAsyncOpSingleThread.java |  37 ++--
 .../manager/zk/TestWtCacheSyncOpSingleThread.java  |  27 +--
 .../helix/manager/zk/TestZNRecordSizeLimit.java    |  30 ++-
 .../manager/zk/TestZkCacheAsyncOpSingleThread.java |  42 ++---
 .../manager/zk/TestZkCacheSyncOpSingleThread.java  |  36 ++--
 .../apache/helix/manager/zk/TestZkFlapping.java    |  83 +++-----
 .../apache/helix/manager/zk/TestZkHelixAdmin.java  |  67 +++----
 .../helix/manager/zk/client/TestHelixZkClient.java |  69 ++++---
 .../org/apache/helix/model/TestConstraint.java     |   2 +-
 .../TestClusterStatusMonitorLifecycle.java         | 115 +++++-------
 .../helix/monitoring/TestZKPathDataDumpTask.java   |  19 +-
 .../mbeans/TestClusterAggregateMetrics.java        |  58 ++++--
 .../store/zk/TestAutoFallbackPropertyStore.java    | 105 ++++++-----
 .../helix/store/zk/TestZkHelixPropertyStore.java   | 104 +++++-----
 .../zk/TestZkManagerWithAutoFallbackStore.java     |  16 +-
 .../helix/task/TaskSynchronizedTestBase.java       |  21 +--
 ...tAssignableInstanceManagerControllerSwitch.java |   1 -
 .../task/TestGetLastScheduledTaskExecInfo.java     |  35 ++--
 .../helix/task/TestGetSetUserContentStore.java     |  13 +-
 .../helix/task/TestSemiAutoStateTransition.java    |   7 +-
 .../helix/task/TestTaskCreateThrottling.java       |  16 +-
 .../org/apache/helix/tools/TestClusterSetup.java   |  79 +++-----
 .../org/apache/helix/tools/TestHelixAdminCli.java  | 209 ++++++++++++---------
 helix-core/src/test/resources/TestJobFailure.json  |   2 +-
 pom.xml                                            |   2 +-
 125 files changed, 2997 insertions(+), 2737 deletions(-)

diff --git a/helix-core/src/main/java/org/apache/helix/ClusterMessagingService.java b/helix-core/src/main/java/org/apache/helix/ClusterMessagingService.java
index 96a5957..28188e0 100644
--- a/helix-core/src/main/java/org/apache/helix/ClusterMessagingService.java
+++ b/helix-core/src/main/java/org/apache/helix/ClusterMessagingService.java
@@ -37,7 +37,7 @@ import org.apache.helix.model.Message;
 public interface ClusterMessagingService {
   /**
    * Send message matching the specifications mentioned in recipientCriteria.
-   * @param receipientCriteria criteria to be met, defined as {@link Criteria}
+   * @param recipientCriteria criteria to be met, defined as {@link Criteria}
    * @See Criteria
    * @param message
    *          message to be sent. Some attributes of this message will be
@@ -55,24 +55,24 @@ public interface ClusterMessagingService {
    * This is useful when message need to be sent and current thread need not
    * wait for response since processing will be done in another thread.
    * @see #send(Criteria, Message)
-   * @param receipientCriteria
+   * @param recipientCriteria
    * @param message
    * @param callbackOnReply callback to trigger on completion
    * @param timeOut Time to wait before failing the send
    * @return the number of messages that were successfully sent
    */
-  int send(Criteria receipientCriteria, Message message, AsyncCallback callbackOnReply, int timeOut);
+  int send(Criteria recipientCriteria, Message message, AsyncCallback callbackOnReply, int timeOut);
 
   /**
    * @see #send(Criteria, Message, AsyncCallback, int)
-   * @param receipientCriteria
+   * @param recipientCriteria
    * @param message
    * @param callbackOnReply
    * @param timeOut
    * @param retryCount maximum number of times to retry the send
    * @return the number of messages that were successfully sent
    */
-  int send(Criteria receipientCriteria, Message message, AsyncCallback callbackOnReply,
+  int send(Criteria recipientCriteria, Message message, AsyncCallback callbackOnReply,
       int timeOut, int retryCount);
 
   /**
@@ -86,14 +86,13 @@ public interface ClusterMessagingService {
    * The current thread can use callbackOnReply instance to store application
    * specific data.
    * @see #send(Criteria, Message, AsyncCallback, int)
-   * @param receipientCriteria
+   * @param recipientCriteria
    * @param message
    * @param callbackOnReply
    * @param timeOut
-   * @param retryCount
    * @return the number of messages that were successfully sent
    */
-  int sendAndWait(Criteria receipientCriteria, Message message, AsyncCallback callbackOnReply,
+  int sendAndWait(Criteria recipientCriteria, Message message, AsyncCallback callbackOnReply,
       int timeOut);
 
   /**
@@ -144,7 +143,7 @@ public interface ClusterMessagingService {
   /**
    * This will generate all messages to be sent given the recipientCriteria and MessageTemplate,
    * the messages are not sent.
-   * @param receipientCriteria criteria to be met, defined as {@link Criteria}
+   * @param recipientCriteria criteria to be met, defined as {@link Criteria}
    * @param messageTemplate the Message on which to base the messages to send
    * @return messages to be sent, grouped by the type of instance to send the message to
    */
diff --git a/helix-core/src/main/java/org/apache/helix/task/TaskDriver.java b/helix-core/src/main/java/org/apache/helix/task/TaskDriver.java
index fb756e8..bf4fdf6 100644
--- a/helix-core/src/main/java/org/apache/helix/task/TaskDriver.java
+++ b/helix-core/src/main/java/org/apache/helix/task/TaskDriver.java
@@ -72,7 +72,7 @@ public class TaskDriver {
   private static final Logger LOG = LoggerFactory.getLogger(TaskDriver.class);
 
   /** Default time out for monitoring workflow or job state */
-  private final static int _defaultTimeout = 3 * 60 * 1000; /* 3 mins */
+  private final static int DEFAULT_TIMEOUT = 5 * 60 * 1000; /* 5 mins */
 
   // HELIX-619 This is a temporary solution for too many ZK nodes issue.
   // Limit workflows/jobs creation to prevent the problem.
@@ -896,7 +896,7 @@ public class TaskDriver {
    */
   public TaskState pollForWorkflowState(String workflowName, TaskState... targetStates)
       throws InterruptedException {
-    return pollForWorkflowState(workflowName, _defaultTimeout, targetStates);
+    return pollForWorkflowState(workflowName, DEFAULT_TIMEOUT, targetStates);
   }
 
   /**
@@ -964,7 +964,7 @@ public class TaskDriver {
    */
   public TaskState pollForJobState(String workflowName, String jobName, TaskState... states)
       throws InterruptedException {
-    return pollForJobState(workflowName, jobName, _defaultTimeout, states);
+    return pollForJobState(workflowName, jobName, DEFAULT_TIMEOUT, states);
   }
 
   /**
diff --git a/helix-core/src/main/java/org/apache/helix/task/TaskUtil.java b/helix-core/src/main/java/org/apache/helix/task/TaskUtil.java
index 9992c2b..ba642ae 100644
--- a/helix-core/src/main/java/org/apache/helix/task/TaskUtil.java
+++ b/helix-core/src/main/java/org/apache/helix/task/TaskUtil.java
@@ -331,7 +331,8 @@ public class TaskUtil {
    */
   protected static String getWorkflowJobUserContent(HelixPropertyStore<ZNRecord> propertyStore,
       String workflowJobResource, String key) {
-    Map<String, String> userContentMap = getWorkflowJobUserContentMap(propertyStore, workflowJobResource);
+    Map<String, String> userContentMap =
+        getWorkflowJobUserContentMap(propertyStore, workflowJobResource);
     return userContentMap != null ? userContentMap.get(key) : null;
   }
 
@@ -343,9 +344,8 @@ public class TaskUtil {
    */
   protected static Map<String, String> getWorkflowJobUserContentMap(
       HelixPropertyStore<ZNRecord> propertyStore, String workflowJobResource) {
-    ZNRecord record = propertyStore.get(Joiner.on("/")
-            .join(TaskConstants.REBALANCER_CONTEXT_ROOT, workflowJobResource, USER_CONTENT_NODE), null,
-        AccessOption.PERSISTENT);
+    ZNRecord record = propertyStore.get(Joiner.on("/").join(TaskConstants.REBALANCER_CONTEXT_ROOT,
+        workflowJobResource, USER_CONTENT_NODE), null, AccessOption.PERSISTENT);
     return record != null ? record.getSimpleFields() : null;
   }
 
@@ -412,9 +412,8 @@ public class TaskUtil {
   protected static Map<String, String> getTaskUserContentMap(
       HelixPropertyStore<ZNRecord> propertyStore, String namespacedJobName,
       String taskPartitionId) {
-    ZNRecord record = propertyStore.get(Joiner.on("/")
-            .join(TaskConstants.REBALANCER_CONTEXT_ROOT, namespacedJobName, USER_CONTENT_NODE), null,
-        AccessOption.PERSISTENT);
+    ZNRecord record = propertyStore.get(Joiner.on("/").join(TaskConstants.REBALANCER_CONTEXT_ROOT,
+        namespacedJobName, USER_CONTENT_NODE), null, AccessOption.PERSISTENT);
     return record != null ? record.getMapField(taskPartitionId) : null;
   }
 
@@ -436,7 +435,8 @@ public class TaskUtil {
   static void addOrUpdateTaskUserContentMap(final HelixPropertyStore<ZNRecord> propertyStore,
       final String job, final String task, final Map<String, String> contentToAddOrUpdate) {
     if (job == null || task == null) {
-      throw new IllegalArgumentException("job and task must be not null when adding task user content");
+      throw new IllegalArgumentException(
+          "job and task must be not null when adding task user content");
     }
     String path =
         Joiner.on("/").join(TaskConstants.REBALANCER_CONTEXT_ROOT, job, USER_CONTENT_NODE);
@@ -693,8 +693,8 @@ public class TaskUtil {
    * @return True if remove success, otherwise false
    */
   protected static boolean removeJobsFromWorkflow(final HelixDataAccessor dataAccessor,
-      final HelixPropertyStore propertyStore, final String workflow, final Set<String> jobs,
-      boolean maintainDependency) {
+      final HelixPropertyStore<ZNRecord> propertyStore, final String workflow,
+      final Set<String> jobs, boolean maintainDependency) {
     boolean success = true;
     if (!removeJobsFromDag(dataAccessor, workflow, jobs, maintainDependency)) {
       LOG.warn("Error occurred while trying to remove jobs + " + jobs + " from the workflow "
@@ -760,8 +760,8 @@ public class TaskUtil {
    * @param job namespaced job name
    * @return
    */
-  protected static boolean removeJob(HelixDataAccessor accessor, HelixPropertyStore propertyStore,
-      String job) {
+  protected static boolean removeJob(HelixDataAccessor accessor,
+      HelixPropertyStore<ZNRecord> propertyStore, String job) {
     if (!removeJobConfig(accessor, job)) {
       LOG.warn(String.format("Error occurred while trying to remove job config for %s.", job));
       return false;
@@ -974,7 +974,6 @@ public class TaskUtil {
     return (jobState != null && jobState != TaskState.NOT_STARTED);
   }
 
-
   /**
    * Clean up all jobs that are COMPLETED and passes its expiry time.
    * @param workflowConfig
@@ -991,17 +990,16 @@ public class TaskUtil {
     long currentTime = System.currentTimeMillis();
     final Set<String> expiredJobs = Sets.newHashSet();
     if (purgeInterval > 0 && workflowContext.getLastJobPurgeTime() + purgeInterval <= currentTime) {
-      expiredJobs.addAll(TaskUtil
-          .getExpiredJobs(manager.getHelixDataAccessor(), manager.getHelixPropertyStore(),
-              workflowConfig, workflowContext));
+      expiredJobs.addAll(TaskUtil.getExpiredJobs(manager.getHelixDataAccessor(),
+          manager.getHelixPropertyStore(), workflowConfig, workflowContext));
       if (expiredJobs.isEmpty()) {
         LOG.info("No job to purge for the queue " + workflow);
       } else {
         LOG.info("Purge jobs " + expiredJobs + " from queue " + workflow);
         Set<String> failedJobRemovals = new HashSet<>();
         for (String job : expiredJobs) {
-          if (!TaskUtil
-              .removeJob(manager.getHelixDataAccessor(), manager.getHelixPropertyStore(), job)) {
+          if (!TaskUtil.removeJob(manager.getHelixDataAccessor(), manager.getHelixPropertyStore(),
+              job)) {
             failedJobRemovals.add(job);
             LOG.warn("Failed to clean up expired and completed jobs from workflow " + workflow);
           }
@@ -1012,11 +1010,10 @@ public class TaskUtil {
         // removal will be tried again at next purge
         expiredJobs.removeAll(failedJobRemovals);
 
-        if (!TaskUtil
-            .removeJobsFromDag(manager.getHelixDataAccessor(), workflow, expiredJobs, true)) {
-          LOG.warn(
-              "Error occurred while trying to remove jobs + " + expiredJobs + " from the workflow "
-                  + workflow);
+        if (!TaskUtil.removeJobsFromDag(manager.getHelixDataAccessor(), workflow, expiredJobs,
+            true)) {
+          LOG.warn("Error occurred while trying to remove jobs + " + expiredJobs
+              + " from the workflow " + workflow);
         }
 
         if (expiredJobs.size() > 0) {
diff --git a/helix-core/src/main/java/org/apache/helix/tools/ClusterStateVerifier.java b/helix-core/src/main/java/org/apache/helix/tools/ClusterStateVerifier.java
index 3ebba04..6d71c04 100644
--- a/helix-core/src/main/java/org/apache/helix/tools/ClusterStateVerifier.java
+++ b/helix-core/src/main/java/org/apache/helix/tools/ClusterStateVerifier.java
@@ -71,7 +71,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * This class is deprecated, please use dedicated verifier classes, such as BestPossibleExternViewVerifier, etc, in tools.ClusterVerifiers
+ * This class is deprecated, please use dedicated verifier classes, such as
+ * BestPossibleExternalViewVerifier, etc, in tools.ClusterVerifiers.
  */
 @Deprecated
 public class ClusterStateVerifier {
diff --git a/helix-core/src/main/java/org/apache/helix/tools/ClusterVerifiers/BestPossibleExternalViewVerifier.java b/helix-core/src/main/java/org/apache/helix/tools/ClusterVerifiers/BestPossibleExternalViewVerifier.java
index 74b9b3c..52ced19 100644
--- a/helix-core/src/main/java/org/apache/helix/tools/ClusterVerifiers/BestPossibleExternalViewVerifier.java
+++ b/helix-core/src/main/java/org/apache/helix/tools/ClusterVerifiers/BestPossibleExternalViewVerifier.java
@@ -201,13 +201,8 @@ public class BestPossibleExternalViewVerifier extends ZkHelixClusterVerifier {
       Map<String, IdealState> idealStates = new HashMap<>(_dataProvider.getIdealStates());
 
       // filter out all resources that use Task state model
-      Iterator<Map.Entry<String, IdealState>> it = idealStates.entrySet().iterator();
-      while (it.hasNext()) {
-        Map.Entry<String, IdealState> pair = it.next();
-        if (pair.getValue().getStateModelDefRef().equals(TaskConstants.STATE_MODEL_NAME)) {
-          it.remove();
-        }
-      }
+      idealStates.entrySet()
+          .removeIf(pair -> pair.getValue().getStateModelDefRef().equals(TaskConstants.STATE_MODEL_NAME));
 
       // verify live instances.
       if (_expectLiveInstances != null && !_expectLiveInstances.isEmpty()) {
diff --git a/helix-core/src/main/java/org/apache/helix/tools/ClusterVerifiers/ZkHelixClusterVerifier.java b/helix-core/src/main/java/org/apache/helix/tools/ClusterVerifiers/ZkHelixClusterVerifier.java
index 9c24f51..2f3b1c6 100644
--- a/helix-core/src/main/java/org/apache/helix/tools/ClusterVerifiers/ZkHelixClusterVerifier.java
+++ b/helix-core/src/main/java/org/apache/helix/tools/ClusterVerifiers/ZkHelixClusterVerifier.java
@@ -45,7 +45,7 @@ public abstract class ZkHelixClusterVerifier
     implements IZkChildListener, IZkDataListener, HelixClusterVerifier {
   private static Logger LOG = LoggerFactory.getLogger(ZkHelixClusterVerifier.class);
   protected static int DEFAULT_TIMEOUT = 300 * 1000;
-  protected static int DEFAULT_PERIOD = 100;
+  protected static int DEFAULT_PERIOD = 500;
 
 
   protected final HelixZkClient _zkClient;
@@ -55,11 +55,7 @@ public abstract class ZkHelixClusterVerifier
   private CountDownLatch _countdown;
 
   private ExecutorService _verifyTaskThreadPool =
-      Executors.newSingleThreadExecutor(new ThreadFactory() {
-        @Override public Thread newThread(Runnable r) {
-          return new Thread(r, "ZkHelixClusterVerifier-verify_thread");
-        }
-      });
+      Executors.newSingleThreadExecutor(r -> new Thread(r, "ZkHelixClusterVerifier-verify_thread"));
 
   protected static class ClusterVerifyTrigger {
     final PropertyKey _triggerKey;
@@ -98,7 +94,7 @@ public abstract class ZkHelixClusterVerifier
     }
     _zkClient = zkClient;
     _clusterName = clusterName;
-    _accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient));
+    _accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_zkClient));
     _keyBuilder = _accessor.keyBuilder();
   }
 
@@ -110,7 +106,7 @@ public abstract class ZkHelixClusterVerifier
         .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddr));
     _zkClient.setZkSerializer(new ZNRecordSerializer());
     _clusterName = clusterName;
-    _accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient));
+    _accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_zkClient));
     _keyBuilder = _accessor.keyBuilder();
   }
 
diff --git a/helix-core/src/test/conf/testng.xml b/helix-core/src/test/conf/testng.xml
index 8847c0f..9411dec 100644
--- a/helix-core/src/test/conf/testng.xml
+++ b/helix-core/src/test/conf/testng.xml
@@ -18,7 +18,7 @@ specific language governing permissions and limitations
 under the License.
 -->
 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
-<suite name="Suite" parallel="none" time-out="300000">
+<suite name="Suite" time-out="300000">
   <test name="Test" preserve-order="true">
     <packages>
         <package name="org.apache.helix.*"/>
diff --git a/helix-core/src/test/java/org/apache/helix/TestHelper.java b/helix-core/src/test/java/org/apache/helix/TestHelper.java
index edc0646..4175968 100644
--- a/helix-core/src/test/java/org/apache/helix/TestHelper.java
+++ b/helix-core/src/test/java/org/apache/helix/TestHelper.java
@@ -301,7 +301,13 @@ public class TestHelper {
       try {
         setup.deleteCluster(clusterName);
       } catch (Exception ex) {
-        LOG.error("Failed to delete cluster " + clusterName, ex);
+        // Failed to delete, give some more time for connections to drop
+        try {
+          Thread.sleep(3000L);
+          setup.deleteCluster(clusterName);
+        } catch (Exception ignored) {
+          // OK - just ignore
+        }
       }
     }
   }
diff --git a/helix-core/src/test/java/org/apache/helix/TestHierarchicalDataStore.java b/helix-core/src/test/java/org/apache/helix/TestHierarchicalDataStore.java
index bd123be..aafcbf1 100644
--- a/helix-core/src/test/java/org/apache/helix/TestHierarchicalDataStore.java
+++ b/helix-core/src/test/java/org/apache/helix/TestHierarchicalDataStore.java
@@ -68,6 +68,8 @@ public class TestHierarchicalDataStore extends ZkUnitTestBase {
     set(path + "/child1", "new child 1 data");
     AssertJUnit.assertTrue(dataHolder.refreshData());
     dataHolder.print();
+
+    deleteCluster("tmp");
   }
 
   private void set(String path, String data) {
diff --git a/helix-core/src/test/java/org/apache/helix/TestZkBasis.java b/helix-core/src/test/java/org/apache/helix/TestZkBasis.java
index 5ef27a5..e7edd1c 100644
--- a/helix-core/src/test/java/org/apache/helix/TestZkBasis.java
+++ b/helix-core/src/test/java/org/apache/helix/TestZkBasis.java
@@ -48,25 +48,24 @@ public class TestZkBasis extends ZkUnitTestBase {
     CountDownLatch _dataDeleteCountDown = new CountDownLatch(1);
 
     @Override
-    public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
+    public void handleChildChange(String parentPath, List<String> currentChilds) {
       _parentPath = parentPath;
       _currentChilds = currentChilds;
       _childChangeCountDown.countDown();
     }
 
     @Override
-    public void handleDataChange(String dataPath, Object data) throws Exception {
+    public void handleDataChange(String dataPath, Object data) {
       // To change body of implemented methods use File | Settings | File Templates.
     }
 
     @Override
-    public void handleDataDeleted(String dataPath) throws Exception {
+    public void handleDataDeleted(String dataPath) {
       _dataDeletePath = dataPath;
       _dataDeleteCountDown.countDown();
     }
   }
 
-
   @Test
   public void testZkSessionExpiry() throws Exception {
     String className = TestHelper.getTestClassName();
@@ -74,9 +73,8 @@ public class TestZkBasis extends ZkUnitTestBase {
     String clusterName = className + "_" + methodName;
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
-    ZkClient client =
-        new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
-            HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
+    ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
+        HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
 
     String path = String.format("/%s", clusterName);
     client.createEphemeral(path);
@@ -96,15 +94,14 @@ public class TestZkBasis extends ZkUnitTestBase {
     String clusterName = className + "_" + methodName;
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
-    ZkClient client =
-        new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
-            HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
+    ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
+        HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
     String path = String.format("/%s", clusterName);
     client.createEphemeral(path);
 
     client.close();
-    Assert.assertFalse(_gZkClient.exists(path), "Ephemeral node: " + path
-        + " should be removed after ZkClient#close()");
+    Assert.assertFalse(_gZkClient.exists(path),
+        "Ephemeral node: " + path + " should be removed after ZkClient#close()");
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -116,19 +113,18 @@ public class TestZkBasis extends ZkUnitTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     final CountDownLatch waitCallback = new CountDownLatch(1);
-    final ZkClient client =
-        new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
-            HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
+    final ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
+        HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
     String path = String.format("/%s", clusterName);
     client.createEphemeral(path);
     client.subscribeDataChanges(path, new IZkDataListener() {
 
       @Override
-      public void handleDataDeleted(String dataPath) throws Exception {
+      public void handleDataDeleted(String dataPath) {
       }
 
       @Override
-      public void handleDataChange(String dataPath, Object data) throws Exception {
+      public void handleDataChange(String dataPath, Object data) {
         client.close();
         waitCallback.countDown();
       }
@@ -159,9 +155,8 @@ public class TestZkBasis extends ZkUnitTestBase {
     String methodName = TestHelper.getTestMethodName();
     String testName = className + "_" + methodName;
 
-    final ZkClient client =
-        new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
-            HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
+    final ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
+        HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
     // make sure "/testName/test" doesn't exist
     final String path = "/" + testName + "/test";
     client.delete(path);
@@ -204,9 +199,8 @@ public class TestZkBasis extends ZkUnitTestBase {
     String methodName = TestHelper.getTestMethodName();
     String testName = className + "_" + methodName;
 
-    final ZkClient client =
-        new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
-            HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
+    final ZkClient client = new ZkClient(ZK_ADDR, HelixZkClient.DEFAULT_SESSION_TIMEOUT,
+        HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
     // make sure "/testName/test" doesn't exist
     final String path = "/" + testName + "/test";
     client.createPersistent(path, true);
@@ -219,8 +213,8 @@ public class TestZkBasis extends ZkUnitTestBase {
     Map<String, Set<IZkDataListener>> dataListenerMap = ZkTestHelper.getZkDataListener(client);
     Assert.assertEquals(dataListenerMap.size(), 1, "ZkClient#_dataListener should have 1 listener");
     Set<IZkDataListener> dataListenerSet = dataListenerMap.get(path);
-    Assert.assertNotNull(dataListenerSet, "ZkClient#_dataListener should have 1 listener on path: "
-        + path);
+    Assert.assertNotNull(dataListenerSet,
+        "ZkClient#_dataListener should have 1 listener on path: " + path);
     Assert.assertEquals(dataListenerSet.size(), 1,
         "ZkClient#_dataListener should have 1 listener on path: " + path);
 
@@ -266,5 +260,6 @@ public class TestZkBasis extends ZkUnitTestBase {
     Assert.assertTrue(childWatch.isEmpty(), "ZooKeeper#watchManager#childWatches should be empty");
 
     client.close();
+    deleteCluster(testName);
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/TestZnodeModify.java b/helix-core/src/test/java/org/apache/helix/TestZnodeModify.java
index e5851f5..a319f3e 100644
--- a/helix-core/src/test/java/org/apache/helix/TestZnodeModify.java
+++ b/helix-core/src/test/java/org/apache/helix/TestZnodeModify.java
@@ -24,7 +24,6 @@ import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import org.apache.helix.manager.zk.ZNRecordSerializer;
 import org.apache.helix.model.IdealState.IdealStateProperty;
 import org.apache.helix.model.IdealState.RebalanceMode;
 import org.apache.helix.tools.TestCommand;
@@ -48,7 +47,7 @@ public class TestZnodeModify extends ZkUnitTestBase {
   @Test()
   public void testBasic() throws Exception {
     logger.info("RUN: " + new Date(System.currentTimeMillis()));
-    List<TestCommand> commandList = new ArrayList<TestCommand>();
+    List<TestCommand> commandList = new ArrayList<>();
 
     // test case for the basic flow, no timeout, no data trigger
     String pathChild1 = PREFIX + "/basic_child1";
@@ -60,7 +59,7 @@ public class TestZnodeModify extends ZkUnitTestBase {
     command = new TestCommand(CommandType.MODIFY, arg);
     commandList.add(command);
 
-    List<String> list = new ArrayList<String>();
+    List<String> list = new ArrayList<>();
     list.add("listValue1");
     list.add("listValue2");
     arg = new ZnodeOpArg(pathChild1, ZnodePropertyType.LIST, "+", "key2", list);
@@ -95,7 +94,7 @@ public class TestZnodeModify extends ZkUnitTestBase {
   @Test()
   public void testDataTrigger() throws Exception {
     logger.info("RUN: " + new Date(System.currentTimeMillis()));
-    List<TestCommand> commandList = new ArrayList<TestCommand>();
+    List<TestCommand> commandList = new ArrayList<>();
 
     // test case for data trigger, no timeout
     String pathChild1 = PREFIX + "/data_trigger_child1";
@@ -133,7 +132,7 @@ public class TestZnodeModify extends ZkUnitTestBase {
 
     Map<TestCommand, Boolean> results = TestExecutor.executeTest(commandList, ZK_ADDR);
 
-    boolean result = results.remove(command1).booleanValue();
+    boolean result = results.remove(command1);
     AssertJUnit.assertFalse(result);
     for (Map.Entry<TestCommand, Boolean> entry : results.entrySet()) {
       Assert.assertTrue(entry.getValue());
@@ -145,7 +144,7 @@ public class TestZnodeModify extends ZkUnitTestBase {
   @Test()
   public void testTimeout() throws Exception {
     logger.info("RUN: " + new Date(System.currentTimeMillis()));
-    List<TestCommand> commandList = new ArrayList<TestCommand>();
+    List<TestCommand> commandList = new ArrayList<>();
 
     // test case for timeout, no data trigger
     String pathChild1 = PREFIX + "/timeout_child1";
@@ -185,7 +184,7 @@ public class TestZnodeModify extends ZkUnitTestBase {
   @Test()
   public void testDataTriggerWithTimeout() throws Exception {
     logger.info("RUN: " + new Date(System.currentTimeMillis()));
-    List<TestCommand> commandList = new ArrayList<TestCommand>();
+    List<TestCommand> commandList = new ArrayList<>();
 
     // test case for data trigger with timeout
     final String pathChild1 = PREFIX + "/dataTriggerWithTimeout_child1";
@@ -204,31 +203,26 @@ public class TestZnodeModify extends ZkUnitTestBase {
     commandList.add(command1);
 
     // start a separate thread to change znode at pathChild1
-    new Thread() {
-      @Override
-      public void run() {
-        try {
-          Thread.sleep(3000);
-          _gZkClient.createPersistent(pathChild1, true);
-          _gZkClient.writeData(pathChild1, record);
-        } catch (InterruptedException e) {
-          logger.error("Interrupted sleep", e);
-        }
+    new Thread(() -> {
+      try {
+        Thread.sleep(3000);
+        _gZkClient.createPersistent(pathChild1, true);
+        _gZkClient.writeData(pathChild1, record);
+      } catch (InterruptedException e) {
+        logger.error("Interrupted sleep", e);
       }
-    }.start();
+    }).start();
 
     Map<TestCommand, Boolean> results = TestExecutor.executeTest(commandList, ZK_ADDR);
     for (Map.Entry<TestCommand, Boolean> entry : results.entrySet()) {
       Assert.assertTrue(entry.getValue());
-      // System.out.println(entry.getValue() + ":" + entry.getKey());
     }
-
   }
 
   @BeforeClass()
   public void beforeClass() {
-    System.out.println("START " + getShortClassName() + " at "
-        + new Date(System.currentTimeMillis()));
+    System.out
+        .println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
     if (_gZkClient.exists(PREFIX)) {
       _gZkClient.deleteRecursively(PREFIX);
     }
@@ -236,6 +230,9 @@ public class TestZnodeModify extends ZkUnitTestBase {
 
   @AfterClass
   public void afterClass() {
+    if (_gZkClient.exists(PREFIX)) {
+      _gZkClient.deleteRecursively(PREFIX);
+    }
     System.out
         .println("END " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
   }
@@ -244,12 +241,12 @@ public class TestZnodeModify extends ZkUnitTestBase {
     ZNRecord record = new ZNRecord("TestDB");
     record.setSimpleField(IdealStateProperty.REBALANCE_MODE.toString(),
         RebalanceMode.CUSTOMIZED.toString());
-    Map<String, String> map = new HashMap<String, String>();
+    Map<String, String> map = new HashMap<>();
     map.put("localhost_12918", "MASTER");
     map.put("localhost_12919", "SLAVE");
     record.setMapField("TestDB_0", map);
 
-    List<String> list = new ArrayList<String>();
+    List<String> list = new ArrayList<>();
     list.add("localhost_12918");
     list.add("localhost_12919");
     record.setListField("TestDB_0", list);
diff --git a/helix-core/src/test/java/org/apache/helix/common/ZkTestBase.java b/helix-core/src/test/java/org/apache/helix/common/ZkTestBase.java
index 721cd33..d759eac 100644
--- a/helix-core/src/test/java/org/apache/helix/common/ZkTestBase.java
+++ b/helix-core/src/test/java/org/apache/helix/common/ZkTestBase.java
@@ -20,6 +20,7 @@ package org.apache.helix.common;
  */
 
 import java.io.IOException;
+import java.lang.management.ManagementFactory;
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Date;
@@ -28,6 +29,8 @@ import java.util.Map;
 import java.util.Set;
 import java.util.logging.Level;
 
+import javax.management.MBeanServerConnection;
+import javax.management.ObjectName;
 import org.I0Itec.zkclient.IZkStateListener;
 import org.I0Itec.zkclient.ZkServer;
 import org.apache.helix.BaseDataAccessor;
@@ -85,6 +88,7 @@ import org.testng.AssertJUnit;
 import org.testng.ITestContext;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.AfterSuite;
+import org.testng.annotations.BeforeClass;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.BeforeSuite;
 
@@ -95,6 +99,7 @@ public class ZkTestBase {
   protected static HelixZkClient _gZkClient;
   protected static ClusterSetup _gSetupTool;
   protected static BaseDataAccessor<ZNRecord> _baseAccessor;
+  protected static MBeanServerConnection _server = ManagementFactory.getPlatformMBeanServer();
 
   public static final String ZK_ADDR = "localhost:2183";
   protected static final String CLUSTER_PREFIX = "CLUSTER";
@@ -102,7 +107,6 @@ public class ZkTestBase {
   protected final String CONTROLLER_PREFIX = "controller";
   protected final String PARTICIPANT_PREFIX = "localhost";
 
-
   @BeforeSuite
   public void beforeSuite() throws Exception {
     // TODO: use logging.properties file to config java.util.logging.Logger levels
@@ -114,7 +118,16 @@ public class ZkTestBase {
     System.setProperty(SystemPropertyKeys.CONTROLLER_MESSAGE_PURGE_DELAY, "3000");
 
     _zkServer = TestHelper.startZkServer(ZK_ADDR);
-    AssertJUnit.assertTrue(_zkServer != null);
+    AssertJUnit.assertNotNull(_zkServer);
+
+    // Clean up all JMX objects
+    for (ObjectName mbean : _server.queryNames(null, null)) {
+      try {
+        _server.unregisterMBean(mbean);
+      } catch (Exception e) {
+        // OK
+      }
+    }
 
     HelixZkClient.ZkClientConfig clientConfig = new HelixZkClient.ZkClientConfig();
     clientConfig.setZkSerializer(new ZNRecordSerializer());
@@ -125,13 +138,39 @@ public class ZkTestBase {
   }
 
   @AfterSuite
-  public void afterSuite() {
+  public void afterSuite() throws IOException {
+    // Clean up all JMX objects
+    for (ObjectName mbean : _server.queryNames(null, null)) {
+      try {
+        _server.unregisterMBean(mbean);
+      } catch (Exception e) {
+        // OK
+      }
+    }
+
     _gZkClient.close();
     TestHelper.stopZkServer(_zkServer);
   }
 
+  @BeforeClass
+  public void beforeClass() throws Exception {
+    // Clean up all JMX objects
+    for (ObjectName mbean : _server.queryNames(null, null)) {
+      try {
+        _server.unregisterMBean(mbean);
+      } catch (Exception e) {
+        // OK
+      }
+    }
+
+    // Giving each test some time to settle (such as gc pause, etc).
+    // Note that this is the best effort we could make to stabilize tests, not a complete solution
+    Runtime.getRuntime().gc();
+    Thread.sleep(1000L);
+  }
+
   @BeforeMethod
-  public void beforeTest(Method testMethod, ITestContext testContext){
+  public void beforeTest(Method testMethod, ITestContext testContext) {
     long startTime = System.currentTimeMillis();
     System.out.println("START " + testMethod.getName() + " at " + new Date(startTime));
     testContext.setAttribute("StartTime", System.currentTimeMillis());
@@ -141,19 +180,17 @@ public class ZkTestBase {
   public void endTest(Method testMethod, ITestContext testContext) {
     Long startTime = (Long) testContext.getAttribute("StartTime");
     long endTime = System.currentTimeMillis();
-    System.out.println(
-        "END " + testMethod.getName() + " at " + new Date(endTime) + ", took: " + (endTime
-            - startTime) + "ms.");
+    System.out.println("END " + testMethod.getName() + " at " + new Date(endTime) + ", took: "
+        + (endTime - startTime) + "ms.");
   }
 
-
   protected String getShortClassName() {
     return this.getClass().getSimpleName();
   }
 
   protected String getCurrentLeader(HelixZkClient zkClient, String clusterName) {
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(zkClient));
     Builder keyBuilder = accessor.keyBuilder();
 
     LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
@@ -193,7 +230,7 @@ public class ZkTestBase {
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
-    if (isNewLeaderElected == false) {
+    if (!isNewLeaderElected) {
       System.out.println("fail to elect a new leader elected in " + clusterName);
     }
     AssertJUnit.assertTrue(isNewLeaderElected);
@@ -308,8 +345,7 @@ public class ZkTestBase {
           IdealState.RebalanceMode.FULL_AUTO + "", rebalanceStrategy);
     }
 
-    idealState =
-        _gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, db);
+    idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, db);
     idealState.setMinActiveReplicas(minActiveReplica);
     if (!idealState.isDelayRebalanceEnabled()) {
       idealState.setDelayRebalanceEnabled(true);
@@ -320,8 +356,7 @@ public class ZkTestBase {
     idealState.setRebalancerClassName(DelayedAutoRebalancer.class.getName());
     _gSetupTool.getClusterManagementTool().setResourceIdealState(clusterName, db, idealState);
     _gSetupTool.rebalanceStorageCluster(clusterName, db, replica);
-    idealState =
-        _gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, db);
+    idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, db);
 
     return idealState;
   }
@@ -329,9 +364,8 @@ public class ZkTestBase {
   protected IdealState createIdealState(String resourceGroupName, String instanceGroupTag,
       List<String> instanceNames, int numPartition, int replica, String rebalanceMode,
       String stateModelDef) {
-    IdealState is = _gSetupTool
-        .createIdealStateForResourceGroup(resourceGroupName, instanceGroupTag, numPartition,
-            replica, rebalanceMode, stateModelDef);
+    IdealState is = _gSetupTool.createIdealStateForResourceGroup(resourceGroupName,
+        instanceGroupTag, numPartition, replica, rebalanceMode, stateModelDef);
 
     // setup initial partition->instance mapping.
     int nodeIdx = 0;
@@ -364,7 +398,8 @@ public class ZkTestBase {
   }
 
   /**
-   * Validate there should be always minimal active replica and top state replica for each partition.
+   * Validate there should be always minimal active replica and top state replica for each
+   * partition.
    * Also make sure there is always some partitions with only active replica count.
    */
   protected void validateMinActiveAndTopStateReplica(IdealState is, ExternalView ev,
@@ -374,8 +409,7 @@ public class ZkTestBase {
     String topState = stateModelDef.getStatesPriorityList().get(0);
     int replica = Integer.valueOf(is.getReplicas());
 
-    Map<String, Integer> stateCount =
-        stateModelDef.getStateCountMap(numNodes, replica);
+    Map<String, Integer> stateCount = stateModelDef.getStateCountMap(numNodes, replica);
     Set<String> activeStates = stateCount.keySet();
 
     for (String partition : is.getPartitionSet()) {
@@ -401,8 +435,8 @@ public class ZkTestBase {
       }
 
       Assert.assertTrue(hasTopState, String.format("%s missing %s replica", partition, topState));
-      Assert.assertTrue(activeReplica >= minActiveReplica, String
-          .format("%s has less active replica %d then required %d", partition, activeReplica,
+      Assert.assertTrue(activeReplica >= minActiveReplica,
+          String.format("%s has less active replica %d then required %d", partition, activeReplica,
               minActiveReplica));
     }
   }
@@ -449,7 +483,8 @@ public class ZkTestBase {
     AssertJUnit.assertEquals(wantEnabled, config.getInstanceEnabled());
   }
 
-  public void verifyReplication(HelixZkClient zkClient, String clusterName, String resource, int repl) {
+  public void verifyReplication(HelixZkClient zkClient, String clusterName, String resource,
+      int repl) {
     ZKHelixDataAccessor accessor =
         new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(zkClient));
     Builder keyBuilder = accessor.keyBuilder();
@@ -464,8 +499,8 @@ public class ZkTestBase {
     }
   }
 
-  protected void simulateSessionExpiry(ZkConnection zkConnection) throws IOException,
-      InterruptedException {
+  protected void simulateSessionExpiry(ZkConnection zkConnection)
+      throws IOException, InterruptedException {
     ZooKeeper oldZookeeper = zkConnection.getZookeeper();
     LOG.info("Old sessionId = " + oldZookeeper.getSessionId());
 
@@ -532,7 +567,7 @@ public class ZkTestBase {
 
   protected void setupStateModel(String clusterName) {
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     Builder keyBuilder = accessor.keyBuilder();
 
     StateModelDefinition masterSlave =
@@ -549,8 +584,8 @@ public class ZkTestBase {
 
   }
 
-  protected Message createMessage(Message.MessageType type, String msgId, String fromState, String toState,
-      String resourceName, String tgtName) {
+  protected Message createMessage(Message.MessageType type, String msgId, String fromState,
+      String toState, String resourceName, String tgtName) {
     Message msg = new Message(type.toString(), msgId);
     msg.setFromState(fromState);
     msg.setToState(toState);
@@ -562,11 +597,11 @@ public class ZkTestBase {
   protected List<IdealState> setupIdealState(String clusterName, int[] nodes, String[] resources,
       int partitions, int replicas) {
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     Builder keyBuilder = accessor.keyBuilder();
 
-    List<IdealState> idealStates = new ArrayList<IdealState>();
-    List<String> instances = new ArrayList<String>();
+    List<IdealState> idealStates = new ArrayList<>();
+    List<String> instances = new ArrayList<>();
     for (int i : nodes) {
       instances.add("localhost_" + i);
     }
@@ -574,7 +609,7 @@ public class ZkTestBase {
     for (String resourceName : resources) {
       IdealState idealState = new IdealState(resourceName);
       for (int p = 0; p < partitions; p++) {
-        List<String> value = new ArrayList<String>();
+        List<String> value = new ArrayList<>();
         for (int r = 0; r < replicas; r++) {
           int n = nodes[(p + r) % nodes.length];
           value.add("localhost_" + n);
@@ -596,7 +631,7 @@ public class ZkTestBase {
 
   protected void setupLiveInstances(String clusterName, int[] liveInstances) {
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     Builder keyBuilder = accessor.keyBuilder();
 
     for (int i = 0; i < liveInstances.length; i++) {
@@ -608,6 +643,16 @@ public class ZkTestBase {
     }
   }
 
+  protected void deleteLiveInstances(String clusterName) {
+    ZKHelixDataAccessor accessor =
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
+    Builder keyBuilder = accessor.keyBuilder();
+
+    for (String liveInstance : accessor.getChildNames(keyBuilder.liveInstances())) {
+      accessor.removeProperty(keyBuilder.liveInstance(liveInstance));
+    }
+  }
+
   protected void setupInstances(String clusterName, int[] instances) {
     HelixAdmin admin = new ZKHelixAdmin(_gZkClient);
     for (int i = 0; i < instances.length; i++) {
@@ -625,8 +670,9 @@ public class ZkTestBase {
       pipeline.handle(event);
       pipeline.finish();
     } catch (Exception e) {
-      LOG.error("Exception while executing pipeline:" + pipeline
-          + ". Will not continue to next pipeline", e);
+      LOG.error(
+          "Exception while executing pipeline:" + pipeline + ". Will not continue to next pipeline",
+          e);
     }
   }
 
@@ -684,8 +730,7 @@ public class ZkTestBase {
 
     /**
      * Instantiate the verifier
-     *
-     * @param clusterName  the cluster to verify
+     * @param clusterName the cluster to verify
      * @param resourceName the resource to verify
      */
     public EmptyZkVerifier(String clusterName, String resourceName) {
@@ -743,4 +788,3 @@ public class ZkTestBase {
     }
   }
 }
-
diff --git a/helix-core/src/test/java/org/apache/helix/controller/rebalancer/TestZeroReplicaAvoidance.java b/helix-core/src/test/java/org/apache/helix/controller/rebalancer/TestZeroReplicaAvoidance.java
index fe5014c..6acbb7f 100644
--- a/helix-core/src/test/java/org/apache/helix/controller/rebalancer/TestZeroReplicaAvoidance.java
+++ b/helix-core/src/test/java/org/apache/helix/controller/rebalancer/TestZeroReplicaAvoidance.java
@@ -1,5 +1,24 @@
 package org.apache.helix.controller.rebalancer;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
@@ -27,37 +46,19 @@ import org.testng.Assert;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
 public class TestZeroReplicaAvoidance extends BaseStageTest {
 
   @Test(dataProvider = "zeroReplicaInput")
   public void testZeroReplicaAvoidanceDuringRebalance(StateModelDefinition stateModelDef,
-      List<String> instancePreferenceList, Map<String, String> currentStateMap, Map<String, List<Message>> pendingMessages,
-      Map<String, String> expectedBestPossibleMap) {
-    System.out.println("START TestDelayedAutoRebalancer at " + new Date(System.currentTimeMillis()));
+      List<String> instancePreferenceList, Map<String, String> currentStateMap,
+      Map<String, List<Message>> pendingMessages, Map<String, String> expectedBestPossibleMap) {
+    System.out
+        .println("START TestDelayedAutoRebalancer at " + new Date(System.currentTimeMillis()));
 
     System.err.println("Test input: " + instancePreferenceList + ":" + currentStateMap + ":");
 
     int numNode = 6;
-    Set<String> liveInstances = new HashSet<String>();
+    Set<String> liveInstances = new HashSet<>();
     for (int i = 0; i < numNode; i++) {
       liveInstances.add("localhost_" + i);
     }
@@ -68,8 +69,8 @@ public class TestZeroReplicaAvoidance extends BaseStageTest {
     DelayedAutoRebalancer rebalancer = new DelayedAutoRebalancer();
     CurrentStateOutput currentStateOutput = new CurrentStateOutput();
     for (String instance : currentStateMap.keySet()) {
-      currentStateOutput
-          .setCurrentState("test", partition, instance, currentStateMap.get(instance));
+      currentStateOutput.setCurrentState("test", partition, instance,
+          currentStateMap.get(instance));
     }
     Set<String> allInstances = new HashSet<>(instancePreferenceList);
     allInstances.addAll(currentStateMap.keySet());
@@ -83,26 +84,25 @@ public class TestZeroReplicaAvoidance extends BaseStageTest {
         }
       }
     }
-    Map<String, String> bestPossibleMap = rebalancer
-        .computeBestPossibleStateForPartition(liveInstances, stateModelDef, instancePreferenceList,
-            currentStateOutput, Collections.<String>emptySet(), is,
-            new ClusterConfig("TestCluster"), partition);
+    Map<String, String> bestPossibleMap = rebalancer.computeBestPossibleStateForPartition(
+        liveInstances, stateModelDef, instancePreferenceList, currentStateOutput,
+        Collections.emptySet(), is, new ClusterConfig("TestCluster"), partition);
     Assert.assertEquals(bestPossibleMap, expectedBestPossibleMap,
         "Differs, get " + bestPossibleMap + "\nexpected: " + expectedBestPossibleMap
             + "\ncurrentState: " + currentStateMap + "\npreferenceList: " + instancePreferenceList);
 
-    System.out.println(
-        "END TestBestPossibleStateCalcStage at " + new Date(System.currentTimeMillis()));
+    System.out
+        .println("END TestBestPossibleStateCalcStage at " + new Date(System.currentTimeMillis()));
   }
 
   @DataProvider(name = "zeroReplicaInput")
   public Object[][] rebalanceStrategies() {
-    List<Object[]> data = new ArrayList<Object[]>();
+    List<Object[]> data = new ArrayList<>();
     data.addAll(loadTestInputs("TestDelayedAutoRebalancer.MasterSlave.json"));
     data.addAll(loadTestInputs("TestDelayedAutoRebalancer.OnlineOffline.json"));
 
     Object[][] ret = new Object[data.size()][];
-    for(int i = 0; i < data.size(); i++) {
+    for (int i = 0; i < data.size(); i++) {
       ret[i] = data.get(i);
     }
     return ret;
@@ -127,7 +127,7 @@ public class TestZeroReplicaAvoidance extends BaseStageTest {
           BuiltInStateModelDefinitions.valueOf(stateModelName).getStateModelDefinition();
 
       List<Map<String, Object>> inputs = (List<Map<String, Object>>) inputMaps.get(INPUT);
-      ret = new ArrayList<Object[]>();
+      ret = new ArrayList<>();
       for (Map<String, Object> inMap : inputs) {
         Map<String, String> currentStates = (Map<String, String>) inMap.get(CURRENT_STATE);
         Map<String, String> bestPossibleStates =
@@ -139,7 +139,7 @@ public class TestZeroReplicaAvoidance extends BaseStageTest {
           Random r = new Random();
           pendingMessages = new HashMap<>();
           for (String instance : pendingStates.keySet()) {
-            pendingMessages.put(instance, new ArrayList<Message>());
+            pendingMessages.put(instance, new ArrayList<>());
             Message m = new Message(new ZNRecord(UUID.randomUUID().toString()));
             m.setFromState(pendingStates.get(instance).split(":")[0]);
             m.setToState(pendingStates.get(instance).split(":")[1]);
@@ -147,7 +147,9 @@ public class TestZeroReplicaAvoidance extends BaseStageTest {
           }
         }
 
-        ret.add(new Object[] { stateModelDef, preferenceList, currentStates, pendingMessages, bestPossibleStates });
+        ret.add(new Object[] {
+            stateModelDef, preferenceList, currentStates, pendingMessages, bestPossibleStates
+        });
       }
     } catch (IOException e) {
       e.printStackTrace();
diff --git a/helix-core/src/test/java/org/apache/helix/controller/stages/BaseStageTest.java b/helix-core/src/test/java/org/apache/helix/controller/stages/BaseStageTest.java
index fa4d3b2..679a5f6 100644
--- a/helix-core/src/test/java/org/apache/helix/controller/stages/BaseStageTest.java
+++ b/helix-core/src/test/java/org/apache/helix/controller/stages/BaseStageTest.java
@@ -106,8 +106,7 @@ public class BaseStageTest {
       int replicas, RebalanceMode rebalanceMode, String stateModelName, String rebalanceClassName,
       String rebalanceStrategyName) {
     List<IdealState> idealStates = new ArrayList<IdealState>();
-    for (int i = 0; i < resources.length; i++) {
-      String resourceName = resources[i];
+    for (String resourceName : resources) {
       ZNRecord record = new ZNRecord(resourceName);
       for (int p = 0; p < partitions; p++) {
         List<String> value = new ArrayList<String>();
diff --git a/helix-core/src/test/java/org/apache/helix/controller/stages/DummyClusterManager.java b/helix-core/src/test/java/org/apache/helix/controller/stages/DummyClusterManager.java
index 9391782..abeb5a9 100644
--- a/helix-core/src/test/java/org/apache/helix/controller/stages/DummyClusterManager.java
+++ b/helix-core/src/test/java/org/apache/helix/controller/stages/DummyClusterManager.java
@@ -74,7 +74,6 @@ public class DummyClusterManager implements HelixManager {
   @Override
   public void disconnect() {
     // TODO Auto-generated method stub
-
   }
 
   @Override
diff --git a/helix-core/src/test/java/org/apache/helix/controller/stages/TestExternalViewStage.java b/helix-core/src/test/java/org/apache/helix/controller/stages/TestExternalViewStage.java
index dabb720..96e334b 100644
--- a/helix-core/src/test/java/org/apache/helix/controller/stages/TestExternalViewStage.java
+++ b/helix-core/src/test/java/org/apache/helix/controller/stages/TestExternalViewStage.java
@@ -1,10 +1,28 @@
 package org.apache.helix.controller.stages;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.List;
 import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.HelixManager;
 import org.apache.helix.TestHelper;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.ZkUnitTestBase;
 import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
 import org.apache.helix.controller.pipeline.Pipeline;
@@ -20,7 +38,7 @@ public class TestExternalViewStage extends ZkUnitTestBase {
     String clusterName = "CLUSTER_" + TestHelper.getTestMethodName();
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     HelixManager manager = new DummyClusterManager(clusterName, accessor);
 
     // ideal state: node0 is MASTER, node1 is SLAVE
@@ -61,6 +79,11 @@ public class TestExternalViewStage extends ZkUnitTestBase {
       Assert.assertEquals(oldExternalViews.get(i).getStat().getVersion(),
           newExternalViews.get(i).getStat().getVersion());
     }
-  }
 
+    if (manager.isConnected()) {
+      manager.disconnect(); // For DummyClusterManager, this is not necessary
+    }
+    deleteLiveInstances(clusterName);
+    deleteCluster(clusterName);
+  }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/controller/stages/TestMessageThrottleStage.java b/helix-core/src/test/java/org/apache/helix/controller/stages/TestMessageThrottleStage.java
index 58b2fc0..fa3e37a 100644
--- a/helix-core/src/test/java/org/apache/helix/controller/stages/TestMessageThrottleStage.java
+++ b/helix-core/src/test/java/org/apache/helix/controller/stages/TestMessageThrottleStage.java
@@ -41,13 +41,10 @@ import org.apache.helix.model.ConstraintItem;
 import org.apache.helix.model.Message;
 import org.apache.helix.model.Message.MessageType;
 import org.apache.helix.model.Partition;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
 public class TestMessageThrottleStage extends ZkUnitTestBase {
-  private static final Logger LOG = LoggerFactory.getLogger(TestMessageThrottleStage.class.getName());
   final String _className = getShortClassName();
 
   @Test
@@ -56,7 +53,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     HelixManager manager = new DummyClusterManager(clusterName, accessor);
 
     // ideal state: node0 is MASTER, node1 is SLAVE
@@ -119,6 +116,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
     Assert.assertEquals(msgThrottleOutput.getMessages("TestDB", new Partition("TestDB_0")).size(),
         1);
 
+    deleteLiveInstances(clusterName);
     deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
@@ -129,7 +127,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     HelixManager manager = new DummyClusterManager(clusterName, accessor);
 
     // ideal state: node0 is MASTER, node1 is SLAVE
@@ -149,14 +147,14 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
 
     // constraint0:
     // "MESSAGE_TYPE=STATE_TRANSITION,CONSTRAINT_VALUE=ANY"
-    record.setMapField("constraint0", new TreeMap<String, String>());
+    record.setMapField("constraint0", new TreeMap<>());
     record.getMapField("constraint0").put("MESSAGE_TYPE", "STATE_TRANSITION");
     record.getMapField("constraint0").put("CONSTRAINT_VALUE", "ANY");
     ConstraintItem constraint0 = new ConstraintItem(record.getMapField("constraint0"));
 
     // constraint1:
     // "MESSAGE_TYPE=STATE_TRANSITION,TRANSITION=OFFLINE-SLAVE,CONSTRAINT_VALUE=ANY"
-    record.setMapField("constraint1", new TreeMap<String, String>());
+    record.setMapField("constraint1", new TreeMap<>());
     record.getMapField("constraint1").put("MESSAGE_TYPE", "STATE_TRANSITION");
     record.getMapField("constraint1").put("TRANSITION", "OFFLINE-SLAVE");
     record.getMapField("constraint1").put("CONSTRAINT_VALUE", "50");
@@ -164,7 +162,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
 
     // constraint2:
     // "MESSAGE_TYPE=STATE_TRANSITION,TRANSITION=OFFLINE-SLAVE,INSTANCE=.*,RESOURCE=TestDB,CONSTRAINT_VALUE=2";
-    record.setMapField("constraint2", new TreeMap<String, String>());
+    record.setMapField("constraint2", new TreeMap<>());
     record.getMapField("constraint2").put("MESSAGE_TYPE", "STATE_TRANSITION");
     record.getMapField("constraint2").put("TRANSITION", "OFFLINE-SLAVE");
     record.getMapField("constraint2").put("INSTANCE", ".*");
@@ -174,7 +172,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
 
     // constraint3:
     // "MESSAGE_TYPE=STATE_TRANSITION,TRANSITION=OFFLINE-SLAVE,INSTANCE=localhost_12918,RESOURCE=.*,CONSTRAINT_VALUE=1";
-    record.setMapField("constraint3", new TreeMap<String, String>());
+    record.setMapField("constraint3", new TreeMap<>());
     record.getMapField("constraint3").put("MESSAGE_TYPE", "STATE_TRANSITION");
     record.getMapField("constraint3").put("TRANSITION", "OFFLINE-SLAVE");
     record.getMapField("constraint3").put("INSTANCE", "localhost_1");
@@ -184,7 +182,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
 
     // constraint4:
     // "MESSAGE_TYPE=STATE_TRANSITION,TRANSITION=OFFLINE-SLAVE,INSTANCE=.*,RESOURCE=.*,CONSTRAINT_VALUE=10"
-    record.setMapField("constraint4", new TreeMap<String, String>());
+    record.setMapField("constraint4", new TreeMap<>());
     record.getMapField("constraint4").put("MESSAGE_TYPE", "STATE_TRANSITION");
     record.getMapField("constraint4").put("TRANSITION", "OFFLINE-SLAVE");
     record.getMapField("constraint4").put("INSTANCE", ".*");
@@ -194,7 +192,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
 
     // constraint5:
     // "MESSAGE_TYPE=STATE_TRANSITION,TRANSITION=OFFLINE-SLAVE,INSTANCE=localhost_12918,RESOURCE=TestDB,CONSTRAINT_VALUE=5"
-    record.setMapField("constraint5", new TreeMap<String, String>());
+    record.setMapField("constraint5", new TreeMap<>());
     record.getMapField("constraint5").put("MESSAGE_TYPE", "STATE_TRANSITION");
     record.getMapField("constraint5").put("TRANSITION", "OFFLINE-SLAVE");
     record.getMapField("constraint5").put("INSTANCE", "localhost_0");
@@ -206,11 +204,6 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
     accessor.setProperty(keyBuilder.constraint(ConstraintType.MESSAGE_CONSTRAINT.toString()),
         new ClusterConstraints(record));
 
-    // ClusterConstraints constraint =
-    // accessor.getProperty(ClusterConstraints.class,
-    // PropertyType.CONFIGS,
-    // ConfigScopeProperty.CONSTRAINT.toString(),
-    // ConstraintType.MESSAGE_CONSTRAINT.toString());
     ClusterConstraints constraint =
         accessor.getProperty(keyBuilder.constraint(ConstraintType.MESSAGE_CONSTRAINT.toString()));
 
@@ -224,7 +217,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
 
     Map<ConstraintAttribute, String> msgAttr = ClusterConstraints.toConstraintAttributes(msg1);
     Set<ConstraintItem> matches = constraint.match(msgAttr);
-    System.out.println(msg1 + " matches(" + matches.size() + "): " + matches);
+
     Assert.assertEquals(matches.size(), 5);
     Assert.assertTrue(containsConstraint(matches, constraint0));
     Assert.assertTrue(containsConstraint(matches, constraint1));
@@ -233,7 +226,6 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
     Assert.assertTrue(containsConstraint(matches, constraint5));
 
     matches = throttleStage.selectConstraints(matches, msgAttr);
-    System.out.println(msg1 + " matches(" + matches.size() + "): " + matches);
     Assert.assertEquals(matches.size(), 2);
     Assert.assertTrue(containsConstraint(matches, constraint1));
     Assert.assertTrue(containsConstraint(matches, constraint5));
@@ -245,7 +237,6 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
 
     msgAttr = ClusterConstraints.toConstraintAttributes(msg2);
     matches = constraint.match(msgAttr);
-    System.out.println(msg2 + " matches(" + matches.size() + "): " + matches);
     Assert.assertEquals(matches.size(), 5);
     Assert.assertTrue(containsConstraint(matches, constraint0));
     Assert.assertTrue(containsConstraint(matches, constraint1));
@@ -254,7 +245,6 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
     Assert.assertTrue(containsConstraint(matches, constraint4));
 
     matches = throttleStage.selectConstraints(matches, msgAttr);
-    System.out.println(msg2 + " matches(" + matches.size() + "): " + matches);
     Assert.assertEquals(matches.size(), 2);
     Assert.assertTrue(containsConstraint(matches, constraint1));
     Assert.assertTrue(containsConstraint(matches, constraint3));
@@ -310,6 +300,7 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
     Assert.assertTrue(throttleMessages.contains(msg3));
     Assert.assertTrue(throttleMessages.contains(msg4));
 
+    deleteLiveInstances(clusterName);
     deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
@@ -322,6 +313,4 @@ public class TestMessageThrottleStage extends ZkUnitTestBase {
     }
     return false;
   }
-
-  // add pending message test case
 }
diff --git a/helix-core/src/test/java/org/apache/helix/controller/stages/TestRebalancePipeline.java b/helix-core/src/test/java/org/apache/helix/controller/stages/TestRebalancePipeline.java
index 4c12774..c3541af 100644
--- a/helix-core/src/test/java/org/apache/helix/controller/stages/TestRebalancePipeline.java
+++ b/helix-core/src/test/java/org/apache/helix/controller/stages/TestRebalancePipeline.java
@@ -28,7 +28,6 @@ import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.HelixManager;
 import org.apache.helix.PropertyKey.Builder;
 import org.apache.helix.TestHelper;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.ZkUnitTestBase;
 import org.apache.helix.controller.dataproviders.ResourceControllerDataProvider;
 import org.apache.helix.controller.pipeline.Pipeline;
@@ -43,14 +42,11 @@ import org.apache.helix.model.CurrentState;
 import org.apache.helix.model.IdealState;
 import org.apache.helix.model.Message;
 import org.apache.helix.model.Partition;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
 public class TestRebalancePipeline extends ZkUnitTestBase {
-  private static final Logger LOG = LoggerFactory.getLogger(TestRebalancePipeline.class.getName());
-  final String _className = getShortClassName();
+  private final String _className = getShortClassName();
 
   @Test
   public void testDuplicateMsg() {
@@ -58,16 +54,17 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     refreshClusterConfig(clusterName, accessor);
     HelixManager manager = new DummyClusterManager(clusterName, accessor);
     ClusterEvent event = new ClusterEvent(ClusterEventType.Unknown);
     event.addAttribute(AttributeName.helixmanager.name(), manager);
-    event.addAttribute(AttributeName.ControllerDataProvider.name(), new ResourceControllerDataProvider());
+    event.addAttribute(AttributeName.ControllerDataProvider.name(),
+        new ResourceControllerDataProvider());
 
     final String resourceName = "testResource_dup";
     String[] resourceGroups = new String[] {
-      resourceName
+        resourceName
     };
     // ideal state: node0 is MASTER, node1 is SLAVE
     // replica=2 means 1 master and 1 slave
@@ -100,8 +97,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
 
     runPipeline(event, dataRefresh);
     runPipeline(event, rebalancePipeline);
-    MessageOutput msgSelOutput =
-        event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
+    MessageOutput msgSelOutput = event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
     List<Message> messages =
         msgSelOutput.getMessages(resourceName, new Partition(resourceName + "_0"));
     Assert.assertEquals(messages.size(), 1, "Should output 1 message: OFFLINE-SLAVE for node0");
@@ -122,6 +118,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     messages = msgSelOutput.getMessages(resourceName, new Partition(resourceName + "_0"));
     Assert.assertEquals(messages.size(), 0, "Should NOT output 1 message: SLAVE-MASTER for node1");
 
+    deleteLiveInstances(clusterName);
     deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
@@ -132,11 +129,11 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     refreshClusterConfig(clusterName, accessor);
     final String resourceName = "testResource_dup";
     String[] resourceGroups = new String[] {
-      resourceName
+        resourceName
     };
 
     TestHelper.setupEmptyCluster(_gZkClient, clusterName);
@@ -208,7 +205,6 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     Thread.sleep(1000);
     Assert.assertTrue(accessor.getChildNames(keyBuilder.messages("localhost_0")).isEmpty());
 
-
     // round4: node0 has duplicated but valid message, i.e. there is a P2P message sent to it
     // due to error in the triggered pipeline, controller should remove duplicated message
     // immediately as the partition has became master 3 sec ago (there is already a timeout)
@@ -231,6 +227,10 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     messages = accessor.getChildNames(keyBuilder.messages("localhost_0"));
     Assert.assertTrue(messages.isEmpty());
 
+    if (controller.isConnected()) {
+      controller.syncStop();
+    }
+    deleteLiveInstances(clusterName);
     deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
@@ -241,7 +241,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     HelixManager manager = new DummyClusterManager(clusterName, accessor);
     ClusterEvent event = new ClusterEvent(ClusterEventType.Unknown);
     event.addAttribute(AttributeName.helixmanager.name(), manager);
@@ -252,7 +252,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
 
     final String resourceName = "testResource_pending";
     String[] resourceGroups = new String[] {
-      resourceName
+        resourceName
     };
     // ideal state: node0 is MASTER, node1 is SLAVE
     // replica=2 means 1 master and 1 slave
@@ -285,8 +285,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
 
     runPipeline(event, dataRefresh);
     runPipeline(event, rebalancePipeline);
-    MessageOutput msgSelOutput =
-        event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
+    MessageOutput msgSelOutput = event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
     List<Message> messages =
         msgSelOutput.getMessages(resourceName, new Partition(resourceName + "_0"));
     Assert.assertEquals(messages.size(), 1, "Should output 1 message: OFFLINE-SLAVE for node0");
@@ -327,6 +326,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     Assert.assertEquals(message.getToState(), "DROPPED");
     Assert.assertEquals(message.getTgtName(), "localhost_0");
 
+    deleteLiveInstances(clusterName);
     deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
@@ -338,16 +338,17 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     HelixManager manager = new DummyClusterManager(clusterName, accessor);
     ClusterEvent event = new ClusterEvent(ClusterEventType.Unknown);
     event.addAttribute(AttributeName.helixmanager.name(), manager);
-    event.addAttribute(AttributeName.ControllerDataProvider.name(), new ResourceControllerDataProvider());
+    event.addAttribute(AttributeName.ControllerDataProvider.name(),
+        new ResourceControllerDataProvider());
     refreshClusterConfig(clusterName, accessor);
 
     final String resourceName = "testResource_xfer";
     String[] resourceGroups = new String[] {
-      resourceName
+        resourceName
     };
     // ideal state: node0 is MASTER, node1 is SLAVE
     // replica=2 means 1 master and 1 slave
@@ -355,7 +356,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
         0, 1
     }, resourceGroups, 1, 2);
     setupLiveInstances(clusterName, new int[] {
-      1
+        1
     });
     setupStateModel(clusterName);
 
@@ -380,8 +381,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
 
     runPipeline(event, dataRefresh);
     runPipeline(event, rebalancePipeline);
-    MessageOutput msgSelOutput =
-        event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
+    MessageOutput msgSelOutput = event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
     List<Message> messages =
         msgSelOutput.getMessages(resourceName, new Partition(resourceName + "_0"));
     Assert.assertEquals(messages.size(), 1, "Should output 1 message: SLAVE-MASTER for node1");
@@ -393,7 +393,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     // round2: updates node0 currentState to SLAVE but keep the
     // message, make sure controller should not send S->M until removal is done
     setupLiveInstances(clusterName, new int[] {
-      0
+        0
     });
     setCurrentState(clusterName, "localhost_0", resourceName, resourceName + "_0", "session_0",
         "SLAVE");
@@ -404,6 +404,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     messages = msgSelOutput.getMessages(resourceName, new Partition(resourceName + "_0"));
     Assert.assertEquals(messages.size(), 0, "Should NOT output 1 message: SLAVE-MASTER for node0");
 
+    deleteLiveInstances(clusterName);
     deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
@@ -415,7 +416,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     HelixManager manager = new DummyClusterManager(clusterName, accessor);
     ClusterEvent event = new ClusterEvent(ClusterEventType.Unknown);
     event.addAttribute(AttributeName.helixmanager.name(), manager);
@@ -453,7 +454,8 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
     rebalancePipeline.addStage(new ResourceMessageDispatchStage());
 
     // set node0 currentState to SLAVE, node1 currentState to MASTER
-    // Helix will try to switch the state of the two instances, but it should not be two MASTER at the same time
+    // Helix will try to switch the state of the two instances, but it should not be two MASTER at
+    // the same time
     // so it should first transit M->S, then transit another instance S->M
     setCurrentState(clusterName, "localhost_0", resourceName, resourceName + "_0", "session_0",
         "SLAVE");
@@ -462,16 +464,17 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
 
     runPipeline(event, dataRefresh);
     runPipeline(event, rebalancePipeline);
-    MessageOutput msgSelOutput =
-        event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
+    MessageOutput msgSelOutput = event.getAttribute(AttributeName.MESSAGES_SELECTED.name());
     List<Message> messages =
         msgSelOutput.getMessages(resourceName, new Partition(resourceName + "_0"));
-    Assert.assertEquals(messages.size(), 1, "Should output 1 message: MASTER-SLAVE for localhost_1");
+    Assert.assertEquals(messages.size(), 1,
+        "Should output 1 message: MASTER-SLAVE for localhost_1");
     Message message = messages.get(0);
     Assert.assertEquals(message.getFromState(), "MASTER");
     Assert.assertEquals(message.getToState(), "SLAVE");
     Assert.assertEquals(message.getTgtName(), "localhost_1");
 
+    deleteLiveInstances(clusterName);
     deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
@@ -484,7 +487,7 @@ public class TestRebalancePipeline extends ZkUnitTestBase {
   private void setCurrentState(String clusterName, String instance, String resourceGroupName,
       String resourceKey, String sessionId, String state, boolean updateTimestamp) {
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     Builder keyBuilder = accessor.keyBuilder();
 
     CurrentState curState = new CurrentState(resourceGroupName);
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestAddClusterV2.java b/helix-core/src/test/java/org/apache/helix/integration/TestAddClusterV2.java
index 73d3208..ef02a41 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestAddClusterV2.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestAddClusterV2.java
@@ -24,31 +24,27 @@ import org.apache.helix.common.ZkTestBase;
 import org.apache.helix.integration.manager.ClusterDistributedController;
 import org.apache.helix.integration.manager.MockParticipantManager;
 import org.apache.helix.tools.ClusterSetup;
-import org.apache.helix.tools.ClusterStateVerifier;
 import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
 import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 public class TestAddClusterV2 extends ZkTestBase {
-  private static Logger LOG = LoggerFactory.getLogger(TestAddClusterV2.class);
-
-  protected static final int CLUSTER_NR = 10;
+  private static final int CLUSTER_NR = 10;
   protected static final int NODE_NR = 5;
   protected static final int START_PORT = 12918;
   protected static final String STATE_MODEL = "MasterSlave";
 
   protected final String CLASS_NAME = getShortClassName();
-  protected final String CONTROLLER_CLUSTER = CONTROLLER_CLUSTER_PREFIX + "_" + CLASS_NAME;
+  private final String CONTROLLER_CLUSTER = CONTROLLER_CLUSTER_PREFIX + "_" + CLASS_NAME;
 
   protected static final String TEST_DB = "TestDB";
 
   MockParticipantManager[] _participants = new MockParticipantManager[NODE_NR];
-  ClusterDistributedController[] _distControllers = new ClusterDistributedController[NODE_NR];
+  private ClusterDistributedController[] _distControllers =
+      new ClusterDistributedController[NODE_NR];
 
   @BeforeClass
   public void beforeClass() throws Exception {
@@ -128,7 +124,7 @@ public class TestAddClusterV2 extends ZkTestBase {
       String clusterName = CLUSTER_PREFIX + "_" + CLASS_NAME + "_" + i;
       deleteCluster(clusterName);
     }
-
+    deleteCluster(CONTROLLER_CLUSTER);
     System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -136,7 +132,7 @@ public class TestAddClusterV2 extends ZkTestBase {
    * verify the external view (against the best possible state)
    * in the controller cluster and the first cluster
    */
-  protected void verifyClusters() {
+  private void verifyClusters() {
     ZkHelixClusterVerifier _clusterVerifier =
         new BestPossibleExternalViewVerifier.Builder(CONTROLLER_CLUSTER).setZkClient(_gZkClient)
             .build();
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestAddNodeAfterControllerStart.java b/helix-core/src/test/java/org/apache/helix/integration/TestAddNodeAfterControllerStart.java
index fd80961..07fc4df 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestAddNodeAfterControllerStart.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestAddNodeAfterControllerStart.java
@@ -21,6 +21,7 @@ package org.apache.helix.integration;
 
 import java.util.Date;
 import java.util.List;
+import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.PropertyPathBuilder;
 import org.apache.helix.TestHelper;
 import org.apache.helix.ZkTestHelper;
@@ -29,14 +30,15 @@ import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.integration.manager.ClusterDistributedController;
 import org.apache.helix.integration.manager.MockParticipantManager;
 import org.apache.helix.manager.zk.CallbackHandler;
+import org.apache.helix.manager.zk.ZKHelixDataAccessor;
 import org.apache.helix.tools.ClusterStateVerifier;
+import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
 public class TestAddNodeAfterControllerStart extends ZkTestBase {
-  private static Logger LOG = LoggerFactory.getLogger(TestAddNodeAfterControllerStart.class);
   final String className = getShortClassName();
 
   @Test
@@ -61,9 +63,8 @@ public class TestAddNodeAfterControllerStart extends ZkTestBase {
     controller.syncStart();
 
     boolean result;
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
     String msgPath = PropertyPathBuilder.instanceMessage(clusterName, "localhost_12918");
     result = checkHandlers(controller.getHandlers(), msgPath);
@@ -74,9 +75,8 @@ public class TestAddNodeAfterControllerStart extends ZkTestBase {
 
     participants[nodeNr - 1] = new MockParticipantManager(ZK_ADDR, clusterName, "localhost_12922");
     new Thread(participants[nodeNr - 1]).start();
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
     msgPath = PropertyPathBuilder.instanceMessage(clusterName, "localhost_12922");
     result = checkHandlers(controller.getHandlers(), msgPath);
@@ -99,8 +99,8 @@ public class TestAddNodeAfterControllerStart extends ZkTestBase {
 
     // setup grand cluster
     final String grandClusterName = "GRAND_" + clusterName;
-    TestHelper.setupCluster(grandClusterName, ZK_ADDR, 0, "controller", null, 0, 0, 1, 0,
-        null, true);
+    TestHelper.setupCluster(grandClusterName, ZK_ADDR, 0, "controller", null, 0, 0, 1, 0, null,
+        true);
 
     ClusterDistributedController distController =
         new ClusterDistributedController(ZK_ADDR, grandClusterName, "controller_0");
@@ -110,11 +110,10 @@ public class TestAddNodeAfterControllerStart extends ZkTestBase {
     _gSetupTool.addCluster(clusterName, true);
     _gSetupTool.activateCluster(clusterName, "GRAND_" + clusterName, true); // addCluster2
 
-    boolean result;
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, "GRAND_" + clusterName));
-    Assert.assertTrue(result);
+    BestPossibleExternalViewVerifier verifier =
+        new BestPossibleExternalViewVerifier.Builder(grandClusterName).setZkAddr(ZK_ADDR)
+            .setZkClient(_gZkClient).build();
+    Assert.assertTrue(verifier.verifyByPolling());
 
     // add node/resource, and do rebalance
     final int nodeNr = 2;
@@ -125,6 +124,10 @@ public class TestAddNodeAfterControllerStart extends ZkTestBase {
 
     _gSetupTool.addResourceToCluster(clusterName, "TestDB0", 1, "LeaderStandby");
     _gSetupTool.rebalanceStorageCluster(clusterName, "TestDB0", 1);
+    BestPossibleExternalViewVerifier verifier2 =
+        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
+            .setZkClient(_gZkClient).build();
+    Assert.assertTrue(verifier2.verifyByPolling());
 
     MockParticipantManager[] participants = new MockParticipantManager[nodeNr];
     for (int i = 0; i < nodeNr - 1; i++) {
@@ -133,10 +136,19 @@ public class TestAddNodeAfterControllerStart extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
-    Assert.assertTrue(result);
+    HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
+    // Make sure new participants are connected
+    for (int i = 0; i < nodeNr - 1; i++) {
+      List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
+      if (!participants[i].isConnected()
+          || !liveInstances.contains(participants[i].getInstanceName())) {
+        Thread.sleep(500L); // Give it more delay
+      }
+    }
+
+    verifier2 = new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
+        .setZkClient(_gZkClient).build();
+    Assert.assertTrue(verifier2.verifyByPolling());
 
     // check if controller_0 has message listener for localhost_12918
     String msgPath = PropertyPathBuilder.instanceMessage(clusterName, "localhost_12918");
@@ -149,10 +161,11 @@ public class TestAddNodeAfterControllerStart extends ZkTestBase {
 
     participants[nodeNr - 1] = new MockParticipantManager(ZK_ADDR, clusterName, "localhost_12919");
     participants[nodeNr - 1].syncStart();
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
-    Assert.assertTrue(result);
+
+    BestPossibleExternalViewVerifier verifier3 =
+        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
+            .setZkClient(_gZkClient).build();
+    Assert.assertTrue(verifier3.verifyByPolling());
     // check if controller_0 has message listener for localhost_12919
     msgPath = PropertyPathBuilder.instanceMessage(clusterName, "localhost_12919");
     numberOfListeners = ZkTestHelper.numberOfListeners(ZK_ADDR, msgPath);
@@ -165,20 +178,17 @@ public class TestAddNodeAfterControllerStart extends ZkTestBase {
       participants[i].syncStop();
     }
     deleteCluster(clusterName);
+    deleteCluster(grandClusterName);
 
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
-  boolean checkHandlers(List<CallbackHandler> handlers, String path) {
-    // System.out.println(handlers.size() + " handlers: ");
+  private boolean checkHandlers(List<CallbackHandler> handlers, String path) {
     for (CallbackHandler handler : handlers) {
-      // System.out.println(handler.getPath());
       if (handler.getPath().equals(path)) {
         return true;
       }
     }
     return false;
   }
-
-  // TODO: need to add a test case for ParticipantCodeRunner
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestAlertingRebalancerFailure.java b/helix-core/src/test/java/org/apache/helix/integration/TestAlertingRebalancerFailure.java
index 7defef4..2ce3266 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestAlertingRebalancerFailure.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestAlertingRebalancerFailure.java
@@ -19,6 +19,7 @@ package org.apache.helix.integration;
  * under the License.
  */
 
+import java.io.IOException;
 import javax.management.MBeanServerConnection;
 import javax.management.MalformedObjectNameException;
 import javax.management.ObjectName;
@@ -56,6 +57,7 @@ import static org.apache.helix.monitoring.mbeans.ClusterStatusMonitor.RESOURCE_D
 import static org.apache.helix.util.StatusUpdateUtil.ErrorType.RebalanceResourceFailure;
 
 public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
+  private static final long TIMEOUT = 180 * 1000L;
   private static final Set<String> _instanceNames = new HashSet<>();
   private static final MBeanServerConnection _server = ManagementFactory.getPlatformMBeanServer();
   protected static final int NODE_NR = 3;
@@ -69,6 +71,15 @@ public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
   public void beforeClass() throws Exception {
     System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
 
+    // Clean up all JMX objects
+    for (ObjectName mbean : _server.queryNames(null, null)) {
+      try {
+        _server.unregisterMBean(mbean);
+      } catch (Exception e) {
+        // OK
+      }
+    }
+
     // setup storage cluster
     _gSetupTool.addCluster(CLUSTER_NAME, true);
 
@@ -100,7 +111,7 @@ public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
   }
 
   @BeforeMethod
-  public void beforeMethod() {
+  public void beforeMethod() throws IOException {
     // Ensure error has been removed
     accessor.removeProperty(errorNodeKey);
   }
@@ -110,12 +121,12 @@ public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
     _gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
         BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO.name());
     _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, 3);
-    ZkHelixClusterVerifier verifier =
-        new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
-            .setResources(new HashSet<>(Collections.singleton(testDb))).build();
+    ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
+        .setZkAddr(ZK_ADDR).setResources(new HashSet<>(Collections.singleton(testDb))).build();
     Assert.assertTrue(verifier.verifyByPolling());
 
-    // disable then enable the resource to ensure no rebalancing error is generated during this process
+    // disable then enable the resource to ensure no rebalancing error is generated during this
+    // process
     _gSetupTool.dropResourceFromCluster(CLUSTER_NAME, testDb);
     _gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
         BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO.name());
@@ -147,13 +158,12 @@ public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
     }
   }
 
-  @Test (dependsOnMethods = "testParticipantUnavailable")
+  @Test(dependsOnMethods = "testParticipantUnavailable")
   public void testTagSetIncorrect() throws Exception {
     _gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
         BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO.name());
-    ZkHelixClusterVerifier verifier =
-        new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
-            .setResources(new HashSet<>(Collections.singleton(testDb))).build();
+    ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
+        .setZkAddr(ZK_ADDR).setResources(new HashSet<>(Collections.singleton(testDb))).build();
     Assert.assertTrue(verifier.verifyByPolling());
 
     // Verify there is no rebalance error logged
@@ -178,7 +188,7 @@ public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
     _gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, testDb);
   }
 
-  @Test (dependsOnMethods = "testTagSetIncorrect")
+  @Test(dependsOnMethods = "testTagSetIncorrect")
   public void testWithDomainId() throws Exception {
     int replicas = 2;
     ConfigAccessor configAccessor = new ConfigAccessor(_gZkClient);
@@ -206,9 +216,8 @@ public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
         BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO.name(),
         CrushRebalanceStrategy.class.getName());
     _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, testDb, replicas);
-    ZkHelixClusterVerifier verifier =
-        new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
-            .setResources(new HashSet<>(Collections.singleton(testDb))).build();
+    ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME)
+        .setZkAddr(ZK_ADDR).setResources(new HashSet<>(Collections.singleton(testDb))).build();
     Assert.assertTrue(verifier.verifyByPolling());
     // Verify there is no rebalance error logged
     Assert.assertNull(accessor.getProperty(errorNodeKey));
@@ -271,49 +280,43 @@ public class TestAlertingRebalancerFailure extends ZkStandAloneCMTestBase {
   }
 
   private void checkRebalanceFailureGauge(final boolean expectFailure) throws Exception {
-    boolean result = TestHelper.verify(new TestHelper.Verifier() {
-      @Override
-      public boolean verify() {
-        try {
-          Long value =
-              (Long) _server.getAttribute(getMbeanName(CLUSTER_NAME), "RebalanceFailureGauge");
-          return value != null && (value == 1) == expectFailure;
-        } catch (Exception e) {
-          return false;
-        }
+    boolean result = TestHelper.verify(() -> {
+      try {
+        Long value =
+            (Long) _server.getAttribute(getMbeanName(CLUSTER_NAME), "RebalanceFailureGauge");
+        return value != null && (value == 1) == expectFailure;
+      } catch (Exception e) {
+        return false;
       }
-    }, 5000); Assert.assertTrue(result);
+    }, TIMEOUT);
+    Assert.assertTrue(result);
   }
 
   private void checkResourceBestPossibleCalFailureState(
       final ResourceMonitor.RebalanceStatus expectedState, final String resourceName)
       throws Exception {
-    boolean result = TestHelper.verify(new TestHelper.Verifier() {
-      @Override
-      public boolean verify() {
-        try {
-          String state = (String) _server
-              .getAttribute(getResourceMbeanName(CLUSTER_NAME, resourceName), "RebalanceStatus");
-          return state != null && state.equals(expectedState.name());
-        } catch (Exception e) {
-          return false;
-        }
+    boolean result = TestHelper.verify(() -> {
+      try {
+        String state = (String) _server
+            .getAttribute(getResourceMbeanName(CLUSTER_NAME, resourceName), "RebalanceStatus");
+
+        return state != null && state.equals(expectedState.name());
+      } catch (Exception e) {
+        return false;
       }
-    }, 5000);
+    }, TIMEOUT);
     Assert.assertTrue(result);
   }
 
   private void pollForError(final HelixDataAccessor accessor, final PropertyKey key)
       throws Exception {
-    boolean result = TestHelper.verify(new TestHelper.Verifier() {
-      @Override
-      public boolean verify() {
-        /* TODO re-enable this check when we start recording rebalance error again
-        return accessor.getProperty(key) != null;
-        */
-        return true;
-      }
-    }, 5000);
+    boolean result = TestHelper.verify(() -> {
+      /*
+       * TODO re-enable this check when we start recording rebalance error again
+       * return accessor.getProperty(key) != null;
+       */
+      return true;
+    }, TIMEOUT);
     Assert.assertTrue(result);
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestBatchMessageHandling.java b/helix-core/src/test/java/org/apache/helix/integration/TestBatchMessageHandling.java
index 713e1e4..c3512af 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestBatchMessageHandling.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestBatchMessageHandling.java
@@ -19,9 +19,13 @@ package org.apache.helix.integration;
  * under the License.
  */
 
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.HelixException;
 import org.apache.helix.NotificationContext;
 import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
+import org.apache.helix.manager.zk.ZKHelixDataAccessor;
 import org.apache.helix.mock.participant.MockMSStateModel;
 import org.apache.helix.model.ExternalView;
 import org.apache.helix.model.IdealState;
@@ -38,7 +42,7 @@ public class TestBatchMessageHandling extends ZkStandAloneCMTestBase {
 
   @Test
   public void testSubMessageFailed() throws InterruptedException {
-    TestOnlineOfflineStateModel._numOfSuccessBeforeFail = 6;
+    TestOnlineOfflineStateModel._numOfSuccessBeforeFailure.set(6);
 
     // Let one instance handle all the batch messages.
     _participants[0].getStateMachineEngine().registerStateModelFactory("OnlineOffline",
@@ -47,17 +51,36 @@ public class TestBatchMessageHandling extends ZkStandAloneCMTestBase {
       _participants[i].syncStop();
     }
 
+    HelixDataAccessor dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
+    // Check that the Participants really stopped
+    for (int i = 1; i < _participants.length; i++) {
+      List<String> liveInstances =
+          dataAccessor.getChildNames(dataAccessor.keyBuilder().liveInstances());
+      if (_participants[i].isConnected()
+          || liveInstances.contains(_participants[i].getInstanceName())) {
+        Thread.sleep(1000L);
+      }
+    }
+
     // Add 1 db with batch message enabled. Each db has 10 partitions.
     // So it will have 1 batch message and 10 sub messages.
-
     String dbName = "TestDBSubMessageFail";
     IdealState idealState = new FullAutoModeISBuilder(dbName).setStateModel("OnlineOffline")
         .setStateModelFactoryName("TestFactory").setNumPartitions(10).setNumReplica(1).build();
     idealState.setBatchMessageMode(true);
     _gSetupTool.getClusterManagementTool().addResource(CLUSTER_NAME, dbName, idealState);
-    _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, 1);
 
+    // Check that IdealState has really been added
+    for (int i = 0; i < 5; i++) {
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, dbName);
+      if (!idealState.equals(is)) {
+        Thread.sleep(1000L);
+      }
+    }
+    _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, 1);
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
+    Thread.sleep(2000L);
 
     int numOfOnlines = 0;
     int numOfErrors = 0;
@@ -67,36 +90,35 @@ public class TestBatchMessageHandling extends ZkStandAloneCMTestBase {
       if (externalView.getStateMap(partition).values().contains("ONLINE")) {
         numOfOnlines++;
       }
-
       if (externalView.getStateMap(partition).values().contains("ERROR")) {
         numOfErrors++;
       }
     }
-
+    if (numOfErrors != 4 || numOfOnlines != 6) {
+      System.out.println("IdealState: " + idealState);
+      System.out.println("ExternalView: " + externalView);
+    }
     Assert.assertEquals(numOfErrors, 4);
     Assert.assertEquals(numOfOnlines, 6);
   }
 
-  public static class TestOnlineOfflineStateModelFactory extends
-      StateModelFactory<TestOnlineOfflineStateModel> {
+  public static class TestOnlineOfflineStateModelFactory
+      extends StateModelFactory<TestOnlineOfflineStateModel> {
     @Override
-    public TestOnlineOfflineStateModel createNewStateModel(String resourceName, String stateUnitKey) {
-      TestOnlineOfflineStateModel model = new TestOnlineOfflineStateModel();
-      return model;
+    public TestOnlineOfflineStateModel createNewStateModel(String resourceName,
+        String stateUnitKey) {
+      return new TestOnlineOfflineStateModel();
     }
   }
 
   public static class TestOnlineOfflineStateModel extends StateModel {
     private static Logger LOG = LoggerFactory.getLogger(MockMSStateModel.class);
-    public static Integer _numOfSuccessBeforeFail;
+    static AtomicInteger _numOfSuccessBeforeFailure = new AtomicInteger();
 
-    public void onBecomeOnlineFromOffline(Message message,
-        NotificationContext context) {
-      synchronized (_numOfSuccessBeforeFail) {
-        if (_numOfSuccessBeforeFail-- > 0) {
-          LOG.info("State transition from Offline to Online");
-          return;
-        }
+    public void onBecomeOnlineFromOffline(Message message, NotificationContext context) {
+      if (_numOfSuccessBeforeFailure.getAndDecrement() > 0) {
+        LOG.info("State transition from Offline to Online");
+        return;
       }
       throw new HelixException("Number of Success reached");
     }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestCMWithFailParticipant.java b/helix-core/src/test/java/org/apache/helix/integration/TestCMWithFailParticipant.java
index 7704ca2..96e7e74 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestCMWithFailParticipant.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestCMWithFailParticipant.java
@@ -63,6 +63,7 @@ public class TestCMWithFailParticipant extends ZkTestBase {
     TestDriver.stopDummyParticipant(uniqClusterName, 2000, 0);
     TestDriver.verifyCluster(uniqClusterName, 3000, 50 * 1000);
     TestDriver.stopCluster(uniqClusterName);
+    deleteCluster(uniqClusterName);
 
     System.out.println("END " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
 
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestCorrectnessOnConnectivityLoss.java b/helix-core/src/test/java/org/apache/helix/integration/TestCorrectnessOnConnectivityLoss.java
index a78e7bf..4bf1ecf 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestCorrectnessOnConnectivityLoss.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestCorrectnessOnConnectivityLoss.java
@@ -75,6 +75,9 @@ public class TestCorrectnessOnConnectivityLoss {
 
   @AfterMethod
   public void afterMethod() {
+    if (_controller.isConnected()) {
+      _controller.disconnect();
+    }
     TestHelper.stopZkServer(_zkServer);
   }
 
@@ -109,6 +112,10 @@ public class TestCorrectnessOnConnectivityLoss {
     Assert.assertEquals(stateReachedCounts.size(), 1);
     Assert.assertTrue(stateReachedCounts.containsKey("ONLINE"));
     Assert.assertEquals(stateReachedCounts.get("ONLINE").intValue(), 1);
+
+    if (participant.isConnected()) {
+      participant.disconnect();
+    }
   }
 
   @SuppressWarnings("deprecation")
@@ -140,6 +147,9 @@ public class TestCorrectnessOnConnectivityLoss {
       Assert.assertEquals(routingTableProvider.getInstances("resource0", "OFFLINE").size(), 0);
     } finally {
       routingTableProvider.shutdown();
+      if (participant.isConnected()) {
+        participant.disconnect();
+      }
     }
   }
 
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestDisable.java b/helix-core/src/test/java/org/apache/helix/integration/TestDisable.java
index 9c10a93..5c177a7 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestDisable.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestDisable.java
@@ -66,7 +66,7 @@ public class TestDisable extends ZkTestBase {
         "MasterSlave", true); // do rebalance
 
     // set ideal state to customized mode
-    ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
+    ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
     ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
     Builder keyBuilder = accessor.keyBuilder();
     IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
@@ -90,7 +90,6 @@ public class TestDisable extends ZkTestBase {
         new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR).build();
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
-
     // disable localhost_12918
     String command =
         "--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " false";
@@ -98,11 +97,12 @@ public class TestDisable extends ZkTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     // make sure localhost_12918 is in OFFLINE state
-    Map<String, Map<String, String>> expectStateMap = new HashMap<String, Map<String, String>>();
-    Map<String, String> expectInstanceStateMap = new HashMap<String, String>();
+    Map<String, Map<String, String>> expectStateMap = new HashMap<>();
+    Map<String, String> expectInstanceStateMap = new HashMap<>();
     expectInstanceStateMap.put(disableNode, "OFFLINE");
     expectStateMap.put(".*", expectInstanceStateMap);
-    boolean result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
+    boolean result =
+        ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
     Assert.assertTrue(result, disableNode + " should be in OFFLINE");
 
     // re-enable localhost_12918
@@ -122,12 +122,12 @@ public class TestDisable extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
   @Test
   public void testDisableNodeAutoIS() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     String clusterName = className + "_" + methodName;
@@ -171,20 +171,20 @@ public class TestDisable extends ZkTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     // make sure localhost_12919 is in OFFLINE state
-    Map<String, Map<String, String>> expectStateMap = new HashMap<String, Map<String, String>>();
-    Map<String, String> expectInstanceStateMap = new HashMap<String, String>();
+    Map<String, Map<String, String>> expectStateMap = new HashMap<>();
+    Map<String, String> expectInstanceStateMap = new HashMap<>();
     expectInstanceStateMap.put(disableNode, "OFFLINE");
     expectStateMap.put(".*", expectInstanceStateMap);
-    boolean result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
+    boolean result =
+        ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
     Assert.assertTrue(result, disableNode + " should be in OFFLINE");
 
     // re-enable localhost_12919
     command =
         "--zkSvr " + ZK_ADDR + " --enableInstance " + clusterName + " " + disableNode + " true";
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // make sure localhost_12919 is NOT in OFFLINE state
@@ -198,6 +198,7 @@ public class TestDisable extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -248,31 +249,29 @@ public class TestDisable extends ZkTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     // disable [TestDB0_0, TestDB0_5] on localhost_12919
-    String command =
-        "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
-            + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
+    String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
+        + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
 
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     // make sure localhost_12918 is in OFFLINE state for [TestDB0_0, TestDB0_5]
-    Map<String, Map<String, String>> expectStateMap = new HashMap<String, Map<String, String>>();
-    Map<String, String> expectInstanceStateMap = new HashMap<String, String>();
+    Map<String, Map<String, String>> expectStateMap = new HashMap<>();
+    Map<String, String> expectInstanceStateMap = new HashMap<>();
     expectInstanceStateMap.put("localhost_12919", "OFFLINE");
     expectStateMap.put("TestDB0_0", expectInstanceStateMap);
     expectStateMap.put("TestDB0_5", expectInstanceStateMap);
-    boolean result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
-    Assert.assertTrue(result, "localhost_12919"
-        + " should be in OFFLINE for [TestDB0_0, TestDB0_5]");
+    boolean result =
+        ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
+    Assert.assertTrue(result,
+        "localhost_12919" + " should be in OFFLINE for [TestDB0_0, TestDB0_5]");
 
     // re-enable localhost_12919 for [TestDB0_0, TestDB0_5]
-    command =
-        "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
-            + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
+    command = "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
+        + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // make sure localhost_12919 is NOT in OFFLINE state for [TestDB0_0, TestDB0_5]
@@ -286,6 +285,7 @@ public class TestDisable extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -328,27 +328,26 @@ public class TestDisable extends ZkTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     // disable [TestDB0_0, TestDB0_5] on localhost_12919
-    String command =
-        "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
-            + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
+    String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
+        + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
 
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     // make sure localhost_12918 is in OFFLINE state for [TestDB0_0, TestDB0_5]
-    Map<String, Map<String, String>> expectStateMap = new HashMap<String, Map<String, String>>();
-    Map<String, String> expectInstanceStateMap = new HashMap<String, String>();
+    Map<String, Map<String, String>> expectStateMap = new HashMap<>();
+    Map<String, String> expectInstanceStateMap = new HashMap<>();
     expectInstanceStateMap.put("localhost_12919", "OFFLINE");
     expectStateMap.put("TestDB0_0", expectInstanceStateMap);
     expectStateMap.put("TestDB0_5", expectInstanceStateMap);
-    boolean result = ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
-    Assert.assertTrue(result, "localhost_12919"
-        + " should be in OFFLINE for [TestDB0_0, TestDB0_5]");
+    boolean result =
+        ZkTestHelper.verifyState(_gZkClient, clusterName, "TestDB0", expectStateMap, "==");
+    Assert.assertTrue(result,
+        "localhost_12919" + " should be in OFFLINE for [TestDB0_0, TestDB0_5]");
 
     // re-enable localhost_12919 for [TestDB0_0, TestDB0_5]
-    command =
-        "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
-            + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
+    command = "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
+        + " localhost_12919 TestDB0 TestDB0_0 TestDB0_5";
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
@@ -363,7 +362,7 @@ public class TestDisable extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
-
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestDisableCustomCodeRunner.java b/helix-core/src/test/java/org/apache/helix/integration/TestDisableCustomCodeRunner.java
index 03f1ea1..dd6aba3 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestDisableCustomCodeRunner.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestDisableCustomCodeRunner.java
@@ -51,8 +51,7 @@ public class TestDisableCustomCodeRunner extends ZkUnitTestBase {
   private static final int PARTITION_NUM = 1;
 
   class DummyCallback implements CustomCodeCallbackHandler {
-    private final Map<NotificationContext.Type, Boolean> _callbackInvokeMap =
-        new HashMap<NotificationContext.Type, Boolean>();
+    private final Map<NotificationContext.Type, Boolean> _callbackInvokeMap = new HashMap<>();
 
     @Override
     public void onCallback(NotificationContext context) {
@@ -64,15 +63,15 @@ public class TestDisableCustomCodeRunner extends ZkUnitTestBase {
       _callbackInvokeMap.clear();
     }
 
-    public boolean isInitTypeInvoked() {
+    boolean isInitTypeInvoked() {
       return _callbackInvokeMap.containsKey(NotificationContext.Type.INIT);
     }
 
-    public boolean isCallbackTypeInvoked() {
+    boolean isCallbackTypeInvoked() {
       return _callbackInvokeMap.containsKey(NotificationContext.Type.CALLBACK);
     }
 
-    public boolean isFinalizeTypeInvoked() {
+    boolean isFinalizeTypeInvoked() {
       return _callbackInvokeMap.containsKey(NotificationContext.Type.FINALIZE);
     }
   }
@@ -99,19 +98,17 @@ public class TestDisableCustomCodeRunner extends ZkUnitTestBase {
     controller.syncStart();
 
     // start participants
-    Map<String, MockParticipantManager> participants =
-        new HashMap<String, MockParticipantManager>();
-    Map<String, HelixCustomCodeRunner> customCodeRunners =
-        new HashMap<String, HelixCustomCodeRunner>();
-    Map<String, DummyCallback> callbacks = new HashMap<String, DummyCallback>();
+    Map<String, MockParticipantManager> participants = new HashMap<>();
+    Map<String, HelixCustomCodeRunner> customCodeRunners = new HashMap<>();
+    Map<String, DummyCallback> callbacks = new HashMap<>();
     for (int i = 0; i < N; i++) {
       String instanceName = "localhost_" + (12918 + i);
 
-      participants
-          .put(instanceName, new MockParticipantManager(ZK_ADDR, clusterName, instanceName));
+      participants.put(instanceName,
+          new MockParticipantManager(ZK_ADDR, clusterName, instanceName));
 
-      customCodeRunners.put(instanceName, new HelixCustomCodeRunner(participants.get(instanceName),
-          ZK_ADDR));
+      customCodeRunners.put(instanceName,
+          new HelixCustomCodeRunner(participants.get(instanceName), ZK_ADDR));
       callbacks.put(instanceName, new DummyCallback());
 
       customCodeRunners.get(instanceName).invoke(callbacks.get(instanceName))
@@ -119,14 +116,12 @@ public class TestDisableCustomCodeRunner extends ZkUnitTestBase {
       participants.get(instanceName).syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier
-            .verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
-                clusterName));
+    boolean result = ClusterStateVerifier.verifyByZkCallback(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // Make sure callback is registered
-    BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
+    BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
     final HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     final String customCodeRunnerResource =
@@ -157,31 +152,27 @@ public class TestDisableCustomCodeRunner extends ZkUnitTestBase {
     admin.enableResource(clusterName, customCodeRunnerResource, false);
 
     // Verify that states of custom-code runner are all OFFLINE
-    result = TestHelper.verify(new TestHelper.Verifier() {
+    result = TestHelper.verify(() -> {
+      PropertyKey.Builder keyBuilder1 = accessor.keyBuilder();
 
-      @Override
-      public boolean verify() throws Exception {
-        PropertyKey.Builder keyBuilder = accessor.keyBuilder();
-
-        ExternalView extView =
-            accessor.getProperty(keyBuilder.externalView(customCodeRunnerResource));
-        if (extView == null) {
-          return false;
-        }
-        Set<String> partitionSet = extView.getPartitionSet();
-        if (partitionSet == null || partitionSet.size() != PARTITION_NUM) {
-          return false;
-        }
-        for (String partition : partitionSet) {
-          Map<String, String> instanceStates = extView.getStateMap(partition);
-          for (String state : instanceStates.values()) {
-            if (!"OFFLINE".equals(state)) {
-              return false;
-            }
+      ExternalView extView1 =
+          accessor.getProperty(keyBuilder1.externalView(customCodeRunnerResource));
+      if (extView1 == null) {
+        return false;
+      }
+      Set<String> partitionSet = extView1.getPartitionSet();
+      if (partitionSet == null || partitionSet.size() != PARTITION_NUM) {
+        return false;
+      }
+      for (String partition : partitionSet) {
+        Map<String, String> instanceStates1 = extView1.getStateMap(partition);
+        for (String state : instanceStates1.values()) {
+          if (!"OFFLINE".equals(state)) {
+            return false;
           }
         }
-        return true;
       }
+      return true;
     }, 10 * 1000);
     Assert.assertTrue(result);
 
@@ -209,10 +200,8 @@ public class TestDisableCustomCodeRunner extends ZkUnitTestBase {
 
     // Re-enable custom-code runner
     admin.enableResource(clusterName, customCodeRunnerResource, true);
-    result =
-        ClusterStateVerifier
-            .verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
-                clusterName));
+    result = ClusterStateVerifier.verifyByZkCallback(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // Verify that custom-invoke is invoked again
@@ -255,6 +244,8 @@ public class TestDisableCustomCodeRunner extends ZkUnitTestBase {
       participant.syncStop();
     }
 
+    deleteLiveInstances(clusterName);
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestDisableExternalView.java b/helix-core/src/test/java/org/apache/helix/integration/TestDisableExternalView.java
index 653dd82..9b44d24 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestDisableExternalView.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestDisableExternalView.java
@@ -160,6 +160,7 @@ public class TestDisableExternalView extends ZkTestBase {
     for (int i = 0; i < NODE_NR; i++) {
       _participants[i].syncStop();
     }
-  }
 
+    deleteCluster(CLUSTER_NAME);
+  }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestDisablePartition.java b/helix-core/src/test/java/org/apache/helix/integration/TestDisablePartition.java
index 902b755..19f9b0b 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestDisablePartition.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestDisablePartition.java
@@ -57,27 +57,25 @@ public class TestDisablePartition extends ZkStandAloneCMTestBase {
     LOG.info("START testDisablePartition() at " + new Date(System.currentTimeMillis()));
 
     // localhost_12919 is MASTER for TestDB_0
-    String command =
-        "--zkSvr " + ZK_ADDR + " --enablePartition false " + CLUSTER_NAME
-            + " localhost_12919 TestDB TestDB_0 TestDB_9";
+    String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + CLUSTER_NAME
+        + " localhost_12919 TestDB TestDB_0 TestDB_9";
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
-    Map<String, Set<String>> map = new HashMap<String, Set<String>>();
+    Map<String, Set<String>> map = new HashMap<>();
     map.put("TestDB_0", TestHelper.setOf("localhost_12919"));
     map.put("TestDB_9", TestHelper.setOf("localhost_12919"));
 
-    boolean result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, CLUSTER_NAME));
+    boolean result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME));
     Assert.assertTrue(result);
 
     TestHelper.verifyState(CLUSTER_NAME, ZK_ADDR, map, "OFFLINE");
 
     ZKHelixAdmin tool = new ZKHelixAdmin(_gZkClient);
-    tool.enablePartition(true, CLUSTER_NAME, "localhost_12919", "TestDB", Arrays.asList("TestDB_9"));
+    tool.enablePartition(true, CLUSTER_NAME, "localhost_12919", "TestDB",
+        Collections.singletonList("TestDB_9"));
 
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, CLUSTER_NAME));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME));
     Assert.assertTrue(result);
 
     map.clear();
@@ -92,10 +90,15 @@ public class TestDisablePartition extends ZkStandAloneCMTestBase {
 
   }
 
-
   @DataProvider(name = "rebalancer")
   public static String[][] rebalancers() {
-    return new String[][] { { AutoRebalancer.class.getName() }, { DelayedAutoRebalancer.class.getName() } };
+    return new String[][] {
+        {
+            AutoRebalancer.class.getName()
+        }, {
+            DelayedAutoRebalancer.class.getName()
+        }
+    };
   }
 
   @Test(dataProvider = "rebalancer", enabled = true)
@@ -171,8 +174,8 @@ public class TestDisablePartition extends ZkStandAloneCMTestBase {
     int[] pid = {
         0, 7
     };
-    for (int i = 0; i < pid.length; i++) {
-      String partitionName = resourceName + '_' + pid[i];
+    for (int value : pid) {
+      String partitionName = resourceName + '_' + value;
       Map<String, String> stateMap = externalView.getStateMap(partitionName);
       String leader = null;
       for (String participantName : stateMap.keySet()) {
@@ -182,8 +185,7 @@ public class TestDisablePartition extends ZkStandAloneCMTestBase {
         }
       }
       List<String> partitionNames = Lists.newArrayList(partitionName);
-      admin.enablePartition(false, clusterName, leader, idealState.getResourceName(),
-          partitionNames);
+      admin.enablePartition(false, clusterName, leader, idealState.getResourceName(), partitionNames);
 
       Thread.sleep(1000);
     }
@@ -204,6 +206,7 @@ public class TestDisablePartition extends ZkStandAloneCMTestBase {
     for (MockParticipantManager participant : participants) {
       participant.syncStop();
     }
-  }
 
+    deleteCluster(clusterName);
+  }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestDisableResource.java b/helix-core/src/test/java/org/apache/helix/integration/TestDisableResource.java
index cc182cc..cbb5b84 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestDisableResource.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestDisableResource.java
@@ -20,6 +20,7 @@ package org.apache.helix.integration;
  */
 
 import java.util.Date;
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import org.apache.helix.BaseDataAccessor;
@@ -38,6 +39,7 @@ import org.apache.helix.model.ExternalView;
 import org.apache.helix.model.IdealState;
 import org.apache.helix.model.IdealState.RebalanceMode;
 import org.apache.helix.tools.ClusterStateVerifier;
+import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
@@ -67,29 +69,44 @@ public class TestDisableResource extends ZkUnitTestBase {
     controller.syncStart();
 
     // start participants
-    MockParticipantManager participants[] = new MockParticipantManager[N];
+    MockParticipantManager[] participants = new MockParticipantManager[N];
     for (int i = 0; i < N; i++) {
       String instanceName = "localhost_" + (12918 + i);
-
       participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
       participants[i].syncStart();
     }
+    // Check for connection status
+    HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
+    for (int i = 0; i < N; i++) {
+      List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
+      if (!liveInstances.contains(participants[i].getInstanceName())) {
+        Thread.sleep(1000L);
+      }
+    }
 
-    boolean result =
-        ClusterStateVerifier
-            .verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
-                clusterName));
+    boolean result = ClusterStateVerifier.verifyByZkCallback(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // Disable TestDB0
     enableResource(clusterName, false);
+    if (_gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, "TestDB0")
+        .isEnabled()) {
+      Thread.sleep(1000L);
+    }
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
+    Assert.assertTrue(result);
     checkExternalView(clusterName);
 
     // Re-enable TestDB0
     enableResource(clusterName, true);
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    if (!_gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, "TestDB0")
+        .isEnabled()) {
+      Thread.sleep(1000L);
+    }
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // Clean up
@@ -97,6 +114,7 @@ public class TestDisableResource extends ZkUnitTestBase {
     for (int i = 0; i < N; i++) {
       participants[i].syncStop();
     }
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -122,29 +140,41 @@ public class TestDisableResource extends ZkUnitTestBase {
     controller.syncStart();
 
     // start participants
-    MockParticipantManager participants[] = new MockParticipantManager[N];
+    MockParticipantManager[] participants = new MockParticipantManager[N];
     for (int i = 0; i < N; i++) {
       String instanceName = "localhost_" + (12918 + i);
-
       participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
       participants[i].syncStart();
     }
-
-    boolean result =
-        ClusterStateVerifier
-            .verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
-                clusterName));
-    Assert.assertTrue(result);
+    // Check for connection status
+    HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
+    for (int i = 0; i < N; i++) {
+      List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
+      if (!liveInstances.contains(participants[i].getInstanceName())) {
+        Thread.sleep(1000L);
+      }
+    }
 
     // disable TestDB0
     enableResource(clusterName, false);
+    if (_gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, "TestDB0")
+        .isEnabled()) {
+      Thread.sleep(1000L);
+    }
+    boolean result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
+    Assert.assertTrue(result);
+
     checkExternalView(clusterName);
 
     // Re-enable TestDB0
     enableResource(clusterName, true);
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    if (!_gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, "TestDB0")
+        .isEnabled()) {
+      Thread.sleep(1000L);
+    }
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // Clean up
@@ -175,8 +205,7 @@ public class TestDisableResource extends ZkUnitTestBase {
         "MasterSlave", RebalanceMode.CUSTOMIZED, true); // do rebalance
 
     // set up custom ideal-state
-    BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
-    HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
+    HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, _baseAccessor);
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
     idealState.setPartitionState("TestDB0_0", "localhost_12918", "SLAVE");
@@ -188,31 +217,43 @@ public class TestDisableResource extends ZkUnitTestBase {
     controller.syncStart();
 
     // start participants
-    MockParticipantManager participants[] = new MockParticipantManager[N];
+    MockParticipantManager[] participants = new MockParticipantManager[N];
     for (int i = 0; i < N; i++) {
       String instanceName = "localhost_" + (12918 + i);
-
       participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
       participants[i].syncStart();
     }
+    // Check for connection status
+    for (int i = 0; i < N; i++) {
+      List<String> liveInstances = accessor.getChildNames(accessor.keyBuilder().liveInstances());
+      if (!liveInstances.contains(participants[i].getInstanceName())) {
+        Thread.sleep(1000L);
+      }
+    }
 
-    boolean result =
-        ClusterStateVerifier
-            .verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
-                clusterName));
-    Assert.assertTrue(result);
+    BestPossibleExternalViewVerifier verifier =
+        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
+            .setZkClient(_gZkClient).build();
 
     // Disable TestDB0
     enableResource(clusterName, false);
+    // Check that the resource has been disabled
+    if (_gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, "TestDB0")
+        .isEnabled()) {
+      Thread.sleep(1000L);
+    }
+    Assert.assertTrue(verifier.verifyByPolling());
+
     checkExternalView(clusterName);
 
     // Re-enable TestDB0
     enableResource(clusterName, true);
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR,
-                clusterName));
-    Assert.assertTrue(result);
+    // Check that the resource has been enabled
+    if (!_gSetupTool.getClusterManagementTool().getResourceIdealState(clusterName, "TestDB0")
+        .isEnabled()) {
+      Thread.sleep(1000L);
+    }
+    Assert.assertTrue(verifier.verifyByPolling());
 
     // Clean up
     controller.syncStop();
@@ -239,30 +280,26 @@ public class TestDisableResource extends ZkUnitTestBase {
     final HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
 
     // verify that states of TestDB0 are all OFFLINE
-    boolean result = TestHelper.verify(new TestHelper.Verifier() {
-
-      @Override
-      public boolean verify() throws Exception {
-        PropertyKey.Builder keyBuilder = accessor.keyBuilder();
+    boolean result = TestHelper.verify(() -> {
+      PropertyKey.Builder keyBuilder = accessor.keyBuilder();
 
-        ExternalView extView = accessor.getProperty(keyBuilder.externalView("TestDB0"));
-        if (extView == null) {
-          return false;
-        }
-        Set<String> partitionSet = extView.getPartitionSet();
-        if (partitionSet == null || partitionSet.size() != PARTITION_NUM) {
-          return false;
-        }
-        for (String partition : partitionSet) {
-          Map<String, String> instanceStates = extView.getStateMap(partition);
-          for (String state : instanceStates.values()) {
-            if (!"OFFLINE".equals(state)) {
-              return false;
-            }
+      ExternalView extView = accessor.getProperty(keyBuilder.externalView("TestDB0"));
+      if (extView == null) {
+        return false;
+      }
+      Set<String> partitionSet = extView.getPartitionSet();
+      if (partitionSet == null || partitionSet.size() != PARTITION_NUM) {
+        return false;
+      }
+      for (String partition : partitionSet) {
+        Map<String, String> instanceStates = extView.getStateMap(partition);
+        for (String state : instanceStates.values()) {
+          if (!"OFFLINE".equals(state)) {
+            return false;
           }
         }
-        return true;
       }
+      return true;
     }, 10 * 1000);
     Assert.assertTrue(result);
   }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestDistributedCMMain.java b/helix-core/src/test/java/org/apache/helix/integration/TestDistributedCMMain.java
index 8ca5980..2496c25 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestDistributedCMMain.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestDistributedCMMain.java
@@ -138,7 +138,7 @@ public class TestDistributedCMMain extends ZkTestBase {
     Assert.assertTrue(result, "first cluster NOT in ideal state");
 
     // stop controller_0-5
-    ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
+    ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_gZkClient);
     ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(controllerClusterName, baseAccessor);
     Builder keyBuilder = accessor.keyBuilder();
     for (int i = 0; i < n; i++) {
@@ -163,11 +163,15 @@ public class TestDistributedCMMain extends ZkTestBase {
     // wait for all zk callbacks done
     System.out.println("Cleaning up...");
     for (int i = 0; i < 2 * n; i++) {
-      controllers[i].syncStop();
+      if (controllers[i] != null && controllers[i].isConnected()) {
+        controllers[i].syncStop();
+      }
     }
 
     for (int i = 0; i < n; i++) {
-      participants[i].syncStop();
+      if (participants[i] != null && participants[i].isConnected()) {
+        participants[i].syncStop();
+      }
     }
 
     for (String cluster : _clusters) {
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestDistributedClusterController.java b/helix-core/src/test/java/org/apache/helix/integration/TestDistributedClusterController.java
index 0403ece..c5dbdd4 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestDistributedClusterController.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestDistributedClusterController.java
@@ -20,6 +20,8 @@ package org.apache.helix.integration;
  */
 
 import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
 import org.apache.helix.PropertyKey.Builder;
 import org.apache.helix.TestHelper;
 import org.apache.helix.ZNRecord;
@@ -44,6 +46,8 @@ public class TestDistributedClusterController extends ZkTestBase {
     final int n = 5;
     final int clusterNb = 10;
 
+    Set<MockParticipantManager> participantRefs = new HashSet<>();
+
     System.out
         .println("START " + clusterNamePrefix + " at " + new Date(System.currentTimeMillis()));
 
@@ -82,10 +86,9 @@ public class TestDistributedClusterController extends ZkTestBase {
       controllers[i].syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(
-            new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, controllerClusterName),
-            30000);
+    boolean result = ClusterStateVerifier.verifyByZkCallback(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, controllerClusterName),
+        30000);
     Assert.assertTrue(result, "Controller cluster NOT in ideal state");
 
     // start first cluster
@@ -95,11 +98,11 @@ public class TestDistributedClusterController extends ZkTestBase {
       String instanceName = "localhost0_" + (12918 + i);
       participants[i] = new MockParticipantManager(ZK_ADDR, firstClusterName, instanceName);
       participants[i].syncStart();
+      participantRefs.add(participants[i]);
     }
 
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            firstClusterName));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, firstClusterName));
     Assert.assertTrue(result, "first cluster NOT in ideal state");
 
     // stop current leader in controller cluster
@@ -118,29 +121,30 @@ public class TestDistributedClusterController extends ZkTestBase {
       String instanceName = "localhost1_" + (12918 + i);
       participants2[i] = new MockParticipantManager(ZK_ADDR, secondClusterName, instanceName);
       participants2[i].syncStart();
+      participantRefs.add(participants2[i]);
     }
 
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            secondClusterName));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, secondClusterName));
     Assert.assertTrue(result, "second cluster NOT in ideal state");
 
     // clean up
     // wait for all zk callbacks done
     System.out.println("Cleaning up...");
     for (int i = 0; i < 5; i++) {
-      result =
-          ClusterStateVerifier
-              .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-                  controllerClusterName));
+      Assert.assertTrue(ClusterStateVerifier
+          .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, controllerClusterName)));
       controllers[i].syncStop();
     }
 
-    for (int i = 0; i < 5; i++) {
-      participants[i].syncStop();
+    for (MockParticipantManager participant : participantRefs) {
+      participant.syncStop();
     }
 
-    System.out.println("END " + clusterNamePrefix + " at " + new Date(System.currentTimeMillis()));
-
+    // delete 10 clusters
+    for (int i = 0; i < clusterNb; i++) {
+      deleteCluster(clusterNamePrefix + "0_" + i);
+    }
+    deleteCluster(controllerClusterName);
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestDrop.java b/helix-core/src/test/java/org/apache/helix/integration/TestDrop.java
index 7d4972d..7dc29c5 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestDrop.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestDrop.java
@@ -29,7 +29,6 @@ import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.HelixDefinedState;
 import org.apache.helix.PropertyKey;
 import org.apache.helix.TestHelper;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.common.ZkTestBase;
 import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.integration.manager.MockParticipantManager;
@@ -55,8 +54,10 @@ public class TestDrop extends ZkTestBase {
    * @param db
    * @param participants
    */
-  private void assertEmptyCSandEV(String clusterName, String db, MockParticipantManager[] participants) {
-    HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+  private void assertEmptyCSandEV(String clusterName, String db,
+      MockParticipantManager[] participants) {
+    HelixDataAccessor accessor =
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     Assert.assertNull(accessor.getProperty(keyBuilder.externalView(db)));
 
@@ -95,7 +96,6 @@ public class TestDrop extends ZkTestBase {
     // start participants
     for (int i = 0; i < n; i++) {
       String instanceName = "localhost_" + (12918 + i);
-
       participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
       participants[i].syncStart();
     }
@@ -112,6 +112,11 @@ public class TestDrop extends ZkTestBase {
 
     assertEmptyCSandEV(clusterName, "TestDB0", participants);
 
+    controller.syncStop();
+    for (int i = 0; i < n; i++) {
+      participants[i].syncStop();
+    }
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -142,7 +147,7 @@ public class TestDrop extends ZkTestBase {
     controller.syncStart();
 
     // start participants
-    Map<String, Set<String>> errTransitions = new HashMap<String, Set<String>>();
+    Map<String, Set<String>> errTransitions = new HashMap<>();
     errTransitions.put("SLAVE-MASTER", TestHelper.setOf("TestDB0_4"));
     errTransitions.put("OFFLINE-SLAVE", TestHelper.setOf("TestDB0_8"));
 
@@ -158,14 +163,13 @@ public class TestDrop extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    Map<String, Map<String, String>> errStateMap = new HashMap<String, Map<String, String>>();
-    errStateMap.put("TestDB0", new HashMap<String, String>());
+    Map<String, Map<String, String>> errStateMap = new HashMap<>();
+    errStateMap.put("TestDB0", new HashMap<>());
     errStateMap.get("TestDB0").put("TestDB0_4", "localhost_12918");
     errStateMap.get("TestDB0").put("TestDB0_8", "localhost_12918");
 
-    ZkHelixClusterVerifier verifier =
-        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
-            .setErrStates(errStateMap).build();
+    ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName)
+        .setZkAddr(ZK_ADDR).setErrStates(errStateMap).build();
     Assert.assertTrue(verifier.verifyByPolling());
 
     // drop resource containing error partitions should drop the partition successfully
@@ -174,8 +178,7 @@ public class TestDrop extends ZkTestBase {
     });
 
     // make sure TestDB0_4 and TestDB0_8 partitions are dropped
-    verifier =
-        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR).build();
+    verifier = new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR).build();
     Assert.assertTrue(verifier.verifyByPolling());
 
     Thread.sleep(400);
@@ -188,12 +191,12 @@ public class TestDrop extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
   @Test
   public void testDropErrorPartitionFailedAutoIS() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     String clusterName = className + "_" + methodName;
@@ -218,7 +221,7 @@ public class TestDrop extends ZkTestBase {
     controller.syncStart();
 
     // start participants
-    Map<String, Set<String>> errTransitions = new HashMap<String, Set<String>>();
+    Map<String, Set<String>> errTransitions = new HashMap<>();
     errTransitions.put("SLAVE-MASTER", TestHelper.setOf("TestDB0_4"));
     errTransitions.put("ERROR-DROPPED", TestHelper.setOf("TestDB0_4"));
 
@@ -235,12 +238,11 @@ public class TestDrop extends ZkTestBase {
     }
 
     Map<String, Map<String, String>> errStateMap = new HashMap<>();
-    errStateMap.put("TestDB0", new HashMap<String, String>());
+    errStateMap.put("TestDB0", new HashMap<>());
     errStateMap.get("TestDB0").put("TestDB0_4", "localhost_12918");
 
-    ZkHelixClusterVerifier verifier =
-        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
-            .setErrStates(errStateMap).build();
+    ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName)
+        .setZkAddr(ZK_ADDR).setErrStates(errStateMap).build();
     Assert.assertTrue(verifier.verifyByPolling());
 
     // drop resource containing error partitions should invoke error->dropped transition
@@ -249,12 +251,12 @@ public class TestDrop extends ZkTestBase {
         "--zkSvr", ZK_ADDR, "--dropResource", clusterName, "TestDB0"
     });
 
-    Thread.sleep(100);
+    Thread.sleep(100L);
     // make sure TestDB0_4 stay in ERROR state and is disabled
     Assert.assertTrue(verifier.verifyByPolling());
 
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     InstanceConfig config = accessor.getProperty(keyBuilder.instanceConfig("localhost_12918"));
     List<String> disabledPartitions = config.getDisabledPartitions();
@@ -263,7 +265,7 @@ public class TestDrop extends ZkTestBase {
     Assert.assertEquals(disabledPartitions.get(0), "TestDB0_4");
 
     // ExternalView should have TestDB0_4->localhost_12918_>ERROR
-    Thread.sleep(100L);
+    Thread.sleep(250L);
     ExternalView ev = accessor.getProperty(keyBuilder.externalView("TestDB0"));
     Set<String> partitions = ev.getPartitionSet();
     Assert.assertEquals(partitions.size(), 1, "Should have TestDB0_4->localhost_12918->ERROR");
@@ -275,8 +277,9 @@ public class TestDrop extends ZkTestBase {
     Assert.assertEquals(stateMap.get("localhost_12918"), HelixDefinedState.ERROR.name());
 
     // localhost_12918 should have TestDB0_4 in ERROR state
-    CurrentState cs = accessor.getProperty(keyBuilder.currentState(participants[0].getInstanceName(),
-        participants[0].getSessionId(), "TestDB0"));
+    CurrentState cs =
+        accessor.getProperty(keyBuilder.currentState(participants[0].getInstanceName(),
+            participants[0].getSessionId(), "TestDB0"));
     Map<String, String> partitionStateMap = cs.getPartitionStateMap();
     Assert.assertEquals(partitionStateMap.size(), 1);
     Assert.assertEquals(partitionStateMap.keySet().iterator().next(), "TestDB0_4");
@@ -286,7 +289,8 @@ public class TestDrop extends ZkTestBase {
     for (int i = 1; i < n; i++) {
       String instanceName = participants[i].getInstanceName();
       String sessionId = participants[i].getSessionId();
-      Assert.assertNull(accessor.getProperty(keyBuilder.currentState(instanceName, sessionId, "TestDB0")));
+      Assert.assertNull(
+          accessor.getProperty(keyBuilder.currentState(instanceName, sessionId, "TestDB0")));
     }
 
     // clean up
@@ -295,6 +299,7 @@ public class TestDrop extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -330,7 +335,7 @@ public class TestDrop extends ZkTestBase {
     isBuilder.assignInstanceAndState("TestDB0_1", "localhost_12918", "SLAVE");
 
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     accessor.setProperty(keyBuilder.idealStates("TestDB0"), isBuilder.build());
 
@@ -340,7 +345,7 @@ public class TestDrop extends ZkTestBase {
     controller.syncStart();
 
     // start participants
-    Map<String, Set<String>> errTransitions = new HashMap<String, Set<String>>();
+    Map<String, Set<String>> errTransitions = new HashMap<>();
     errTransitions.put("SLAVE-MASTER", TestHelper.setOf("TestDB0_0"));
 
     for (int i = 0; i < n; i++) {
@@ -355,13 +360,12 @@ public class TestDrop extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    Map<String, Map<String, String>> errStateMap = new HashMap<String, Map<String, String>>();
-    errStateMap.put("TestDB0", new HashMap<String, String>());
+    Map<String, Map<String, String>> errStateMap = new HashMap<>();
+    errStateMap.put("TestDB0", new HashMap<>());
     errStateMap.get("TestDB0").put("TestDB0_0", "localhost_12918");
 
-    ZkHelixClusterVerifier verifier =
-        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR)
-            .setErrStates(errStateMap).build();
+    ZkHelixClusterVerifier verifier = new BestPossibleExternalViewVerifier.Builder(clusterName)
+        .setZkAddr(ZK_ADDR).setErrStates(errStateMap).build();
     Assert.assertTrue(verifier.verifyByPolling());
 
     // drop resource containing error partitions should drop the partition successfully
@@ -370,8 +374,7 @@ public class TestDrop extends ZkTestBase {
     });
 
     // make sure TestDB0_0 partition is dropped
-    verifier =
-        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR).build();
+    verifier = new BestPossibleExternalViewVerifier.Builder(clusterName).setZkAddr(ZK_ADDR).build();
     Assert.assertTrue(verifier.verifyByPolling(), "Should be empty exeternal-view");
     Thread.sleep(400);
 
@@ -383,6 +386,7 @@ public class TestDrop extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -425,9 +429,8 @@ public class TestDrop extends ZkTestBase {
     Assert.assertTrue(verifier.verifyByPolling());
 
     // add schemata resource group
-    String command =
-        "--zkSvr " + ZK_ADDR + " --addResource " + clusterName
-            + " schemata 1 STORAGE_DEFAULT_SM_SCHEMATA";
+    String command = "--zkSvr " + ZK_ADDR + " --addResource " + clusterName
+        + " schemata 1 STORAGE_DEFAULT_SM_SCHEMATA";
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
     command = "--zkSvr " + ZK_ADDR + " --rebalance " + clusterName + " schemata " + n;
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
@@ -450,6 +453,7 @@ public class TestDrop extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestEnableCompression.java b/helix-core/src/test/java/org/apache/helix/integration/TestEnableCompression.java
index cde62ae..4d906ed 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestEnableCompression.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestEnableCompression.java
@@ -46,7 +46,6 @@ import org.testng.annotations.Test;
 public class TestEnableCompression extends ZkTestBase {
   @Test()
   public void testEnableCompressionResource() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     String clusterName = className + "_" + methodName;
@@ -104,12 +103,11 @@ public class TestEnableCompression extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName), 120000);
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName), 120000);
     Assert.assertTrue(result);
 
-    List<String> compressedPaths = new ArrayList<String>();
+    List<String> compressedPaths = new ArrayList<>();
     findCompressedZNodes(zkClient, "/" + clusterName, compressedPaths);
 
     System.out.println("compressed paths:" + compressedPaths);
@@ -126,10 +124,12 @@ public class TestEnableCompression extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
-  private void findCompressedZNodes(HelixZkClient zkClient, String path, List<String> compressedPaths) {
+  private void findCompressedZNodes(HelixZkClient zkClient, String path,
+      List<String> compressedPaths) {
     List<String> children = zkClient.getChildren(path);
     if (children != null && children.size() > 0) {
       for (String child : children) {
@@ -138,10 +138,9 @@ public class TestEnableCompression extends ZkTestBase {
       }
     } else {
       byte[] data = zkClient.readData(path);
-      if (data != null && GZipCompressionUtil.isCompressed(data)) {
+      if (GZipCompressionUtil.isCompressed(data)) {
         compressedPaths.add(path);
       }
     }
-
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestEnablePartitionDuringDisable.java b/helix-core/src/test/java/org/apache/helix/integration/TestEnablePartitionDuringDisable.java
index facd19e..ca47e9c 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestEnablePartitionDuringDisable.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestEnablePartitionDuringDisable.java
@@ -38,10 +38,6 @@ import org.testng.annotations.Test;
 public class TestEnablePartitionDuringDisable extends ZkTestBase {
   private static Logger LOG = LoggerFactory.getLogger(TestEnablePartitionDuringDisable.class);
 
-  static {
-    // Logger.getRootLogger().setLevel(Level.INFO);
-  }
-
   class EnablePartitionTransition extends MockTransition {
     int slaveToOfflineCnt = 0;
     int offlineToSlave = 0;
@@ -60,16 +56,16 @@ public class TestEnablePartitionDuringDisable extends ZkTestBase {
           slaveToOfflineCnt++;
 
           try {
-            String command =
-                "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
-                    + " localhost_12919 TestDB0 TestDB0_0";
+            String command = "--zkSvr " + ZK_ADDR + " --enablePartition true " + clusterName
+                + " localhost_12919 TestDB0 TestDB0_0";
 
             ClusterSetup.processCommandLineArgs(command.split("\\s+"));
           } catch (Exception e) {
             LOG.error("Exception in cluster setup", e);
           }
 
-        } else if (slaveToOfflineCnt > 0 && fromState.equals("OFFLINE") && toState.equals("SLAVE")) {
+        } else if (slaveToOfflineCnt > 0 && fromState.equals("OFFLINE")
+            && toState.equals("SLAVE")) {
           offlineToSlave++;
         }
       }
@@ -114,15 +110,13 @@ public class TestEnablePartitionDuringDisable extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    boolean result = ClusterStateVerifier.verifyByZkCallback(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // disable partitions
-    String command =
-        "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
-            + " localhost_12919 TestDB0 TestDB0_0";
+    String command = "--zkSvr " + ZK_ADDR + " --enablePartition false " + clusterName
+        + " localhost_12919 TestDB0 TestDB0_0";
 
     ClusterSetup.processCommandLineArgs(command.split("\\s+"));
 
@@ -147,6 +141,7 @@ public class TestEnablePartitionDuringDisable extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
   }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestErrorPartition.java b/helix-core/src/test/java/org/apache/helix/integration/TestErrorPartition.java
index e407424..6806969 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestErrorPartition.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestErrorPartition.java
@@ -19,7 +19,7 @@ package org.apache.helix.integration;
  * under the License.
  */
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
@@ -67,12 +67,11 @@ public class TestErrorPartition extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    Map<String, Map<String, String>> errStates = new HashMap<String, Map<String, String>>();
-    errStates.put("TestDB0", new HashMap<String, String>());
+    Map<String, Map<String, String>> errStates = new HashMap<>();
+    errStates.put("TestDB0", new HashMap<>());
     errStates.get("TestDB0").put("TestDB0_4", "localhost_12918");
-    boolean result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName, errStates));
+    boolean result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName, errStates));
     Assert.assertTrue(result);
 
     Map<String, Set<String>> errorStateMap = new HashMap<String, Set<String>>() {
@@ -86,11 +85,10 @@ public class TestErrorPartition extends ZkTestBase {
 
     // disable a partition on a node with error state
     tool.enablePartition(false, clusterName, "localhost_12918", "TestDB0",
-        Arrays.asList("TestDB0_4"));
+        Collections.singletonList("TestDB0_4"));
 
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName, errStates));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName, errStates));
     Assert.assertTrue(result);
 
     TestHelper.verifyState(clusterName, ZK_ADDR, errorStateMap, "ERROR");
@@ -98,27 +96,24 @@ public class TestErrorPartition extends ZkTestBase {
     // disable a node with error state
     tool.enableInstance(clusterName, "localhost_12918", false);
 
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName, errStates));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName, errStates));
     Assert.assertTrue(result);
 
     // make sure after restart stale ERROR state is gone
     tool.enablePartition(true, clusterName, "localhost_12918", "TestDB0",
-        Arrays.asList("TestDB0_4"));
+        Collections.singletonList("TestDB0_4"));
     tool.enableInstance(clusterName, "localhost_12918", true);
 
     participants[0].syncStop();
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
     participants[0] = new MockParticipantManager(ZK_ADDR, clusterName, "localhost_12918");
     new Thread(participants[0]).start();
 
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // clean up
@@ -127,6 +122,7 @@ public class TestErrorPartition extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END testErrorPartition() at " + new Date(System.currentTimeMillis()));
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestExternalViewUpdates.java b/helix-core/src/test/java/org/apache/helix/integration/TestExternalViewUpdates.java
index de90677..b6058e9 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestExternalViewUpdates.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestExternalViewUpdates.java
@@ -85,11 +85,11 @@ public class TestExternalViewUpdates extends ZkTestBase {
     // 10 Resources, 1 partition, 1 replica, so there are at most 10 ZK writes for EV (assume)
     // worst case that no event is batched in controller. Therefore, EV version should be < 10
     Builder keyBuilder = new Builder(clusterName);
-    BaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
+    BaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient);
     String parentPath = keyBuilder.externalViews().getPath();
     List<String> childNames = accessor.getChildNames(parentPath, 0);
 
-    List<String> paths = new ArrayList<String>();
+    List<String> paths = new ArrayList<>();
     for (String name : childNames) {
       paths.add(parentPath + "/" + name);
     }
@@ -106,6 +106,7 @@ public class TestExternalViewUpdates extends ZkTestBase {
     for (int i = 0; i < 5; i++) {
       participants[i].syncStop();
     }
+    deleteCluster(clusterName);
     System.out.println("END testExternalViewUpdates at " + new Date(System.currentTimeMillis()));
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestHelixCustomCodeRunner.java b/helix-core/src/test/java/org/apache/helix/integration/TestHelixCustomCodeRunner.java
index 20dce89..4d8a3c6 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestHelixCustomCodeRunner.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestHelixCustomCodeRunner.java
@@ -24,10 +24,8 @@ import org.apache.helix.HelixConstants.ChangeType;
 import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.HelixManager;
 import org.apache.helix.NotificationContext;
-import org.apache.helix.NotificationContext.Type;
 import org.apache.helix.PropertyKey.Builder;
 import org.apache.helix.TestHelper;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.common.ZkTestBase;
 import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.integration.manager.MockParticipantManager;
@@ -46,8 +44,6 @@ public class TestHelixCustomCodeRunner extends ZkTestBase {
   private static Logger LOG = LoggerFactory.getLogger(TestHelixCustomCodeRunner.class);
 
   private final String _clusterName = "CLUSTER_" + getShortClassName();
-  private final int _nodeNb = 5;
-  private final int _startPort = 12918;
   private final MockCallback _callback = new MockCallback();
 
   class MockCallback implements CustomCodeCallbackHandler {
@@ -55,8 +51,6 @@ public class TestHelixCustomCodeRunner extends ZkTestBase {
 
     @Override
     public void onCallback(NotificationContext context) {
-      HelixManager manager = context.getManager();
-      Type type = context.getType();
       _isCallbackInvoked = true;
       // System.out.println(type + ": TestCallback invoked on " + manager.getInstanceName());
     }
@@ -83,13 +77,15 @@ public class TestHelixCustomCodeRunner extends ZkTestBase {
   public void testCustomCodeRunner() throws Exception {
     System.out.println("START " + _clusterName + " at " + new Date(System.currentTimeMillis()));
 
-    TestHelper.setupCluster(_clusterName, ZK_ADDR, _startPort, "localhost", // participant name
-                                                                            // prefix
+    int nodeNb = 5;
+    int startPort = 12918;
+    TestHelper.setupCluster(_clusterName, ZK_ADDR, startPort, "localhost", // participant name
+                                                                           // prefix
         "TestDB", // resource name prefix
         1, // resourceNb
         5, // partitionNb
-        _nodeNb, // nodesNb
-        _nodeNb, // replica
+        nodeNb, // nodesNb
+        nodeNb, // replica
         "MasterSlave", true);
 
     ClusterControllerManager controller =
@@ -97,17 +93,16 @@ public class TestHelixCustomCodeRunner extends ZkTestBase {
     controller.syncStart();
 
     MockParticipantManager[] participants = new MockParticipantManager[5];
-    for (int i = 0; i < _nodeNb; i++) {
-      String instanceName = "localhost_" + (_startPort + i);
+    for (int i = 0; i < nodeNb; i++) {
+      String instanceName = "localhost_" + (startPort + i);
 
       participants[i] = new MockParticipantManager(ZK_ADDR, _clusterName, instanceName);
 
       registerCustomCodeRunner(participants[i]);
       participants[i].syncStart();
     }
-    boolean result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, _clusterName));
+    boolean result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName));
     Assert.assertTrue(result);
 
     Thread.sleep(1000); // wait for the INIT type callback to finish
@@ -116,7 +111,7 @@ public class TestHelixCustomCodeRunner extends ZkTestBase {
 
     // add a new live instance
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     Builder keyBuilder = accessor.keyBuilder();
 
     LiveInstance newLiveIns = new LiveInstance("newLiveInstance");
@@ -129,7 +124,7 @@ public class TestHelixCustomCodeRunner extends ZkTestBase {
 
     // clean up
     controller.syncStop();
-    for (int i = 0; i < _nodeNb; i++) {
+    for (int i = 0; i < nodeNb; i++) {
       participants[i].syncStop();
     }
     accessor.removeProperty(keyBuilder.liveInstance("newLiveInstance"));
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestHelixUsingDifferentParams.java b/helix-core/src/test/java/org/apache/helix/integration/TestHelixUsingDifferentParams.java
index d59a8e6..71738e2 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestHelixUsingDifferentParams.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestHelixUsingDifferentParams.java
@@ -30,32 +30,30 @@ public class TestHelixUsingDifferentParams extends ZkTestBase {
 
   @Test()
   public void testCMUsingDifferentParams() throws Exception {
-    System.out.println("START " + getShortClassName() + " at "
-        + new Date(System.currentTimeMillis()));
+    System.out
+        .println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
 
-    int numResourceArray[] = new int[] {
-      1
-    }; // , 2}; // , 3, 6};
-    int numPartitionsPerResourceArray[] = new int[] {
-      10
-    }; // , 20, 50, 100}; // ,
-    // 1000};
-    int numInstances[] = new int[] {
-      5
-    }; // , 10}; // , 50, 100, 1000};
-    int replicas[] = new int[] {
-      2
-    }; // , 3}; //, 4, 5};
+    int[] numResourceArray = new int[] {
+        1
+    };
+    int[] numPartitionsPerResourceArray = new int[] {
+        10
+    };
+    int[] numInstances = new int[] {
+        5
+    };
+    int[] replicas = new int[] {
+        2
+    };
 
     for (int numResources : numResourceArray) {
       for (int numPartitionsPerResource : numPartitionsPerResourceArray) {
         for (int numInstance : numInstances) {
           for (int replica : replicas) {
-            String uniqClusterName =
-                "TestDiffParam_" + "rg" + numResources + "_p" + numPartitionsPerResource + "_n"
-                    + numInstance + "_r" + replica;
-            System.out.println("START " + uniqClusterName + " at "
-                + new Date(System.currentTimeMillis()));
+            String uniqClusterName = "TestDiffParam_" + "rg" + numResources + "_p"
+                + numPartitionsPerResource + "_n" + numInstance + "_r" + replica;
+            System.out.println(
+                "START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
 
             TestDriver.setupCluster(uniqClusterName, ZK_ADDR, numResources,
                 numPartitionsPerResource, numInstance, replica);
@@ -67,9 +65,9 @@ public class TestHelixUsingDifferentParams extends ZkTestBase {
             TestDriver.startController(uniqClusterName);
             TestDriver.verifyCluster(uniqClusterName, 1000, 50 * 1000);
             TestDriver.stopCluster(uniqClusterName);
-
-            System.out.println("END " + uniqClusterName + " at "
-                + new Date(System.currentTimeMillis()));
+            deleteCluster(uniqClusterName);
+            System.out
+                .println("END " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
           }
         }
       }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestPartitionMovementThrottle.java b/helix-core/src/test/java/org/apache/helix/integration/TestPartitionMovementThrottle.java
index b14cdb5..dbc8f90 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestPartitionMovementThrottle.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestPartitionMovementThrottle.java
@@ -22,7 +22,6 @@ package org.apache.helix.integration;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
-import java.util.Comparator;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -49,8 +48,8 @@ import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
-  ConfigAccessor _configAccessor;
-  Set<String> _dbs = new HashSet<String>();
+  private ConfigAccessor _configAccessor;
+  private Set<String> _dbs = new HashSet<>();
 
   @Override
   @BeforeClass
@@ -83,7 +82,8 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
 
     setupThrottleConfig();
 
-    _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR).build();
+    _clusterVerifier =
+        new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR).build();
   }
 
   private void setupThrottleConfig() {
@@ -110,9 +110,8 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
         StateTransitionThrottleConfig.ThrottleScope.CLUSTER, 100);
 
     clusterConfig
-        .setStateTransitionThrottleConfigs(Arrays
-            .asList(resourceLoadThrottle, instanceLoadThrottle, clusterLoadThrottle,
-                resourceRecoveryThrottle, clusterRecoveryThrottle));
+        .setStateTransitionThrottleConfigs(Arrays.asList(resourceLoadThrottle, instanceLoadThrottle,
+            clusterLoadThrottle, resourceRecoveryThrottle, clusterRecoveryThrottle));
 
     clusterConfig.setPersistIntermediateAssignment(true);
     _configAccessor.setClusterConfig(CLUSTER_NAME, clusterConfig);
@@ -160,15 +159,14 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
     for (int i = 0; i < NODE_NR - 2; i++) {
       _participants[i].syncStart();
     }
-    _gSetupTool.addResourceToCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, 10, STATE_MODEL,
-        RebalanceMode.FULL_AUTO.name());
+    _gSetupTool.addResourceToCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, 10,
+        STATE_MODEL, RebalanceMode.FULL_AUTO.name());
     _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, _replica);
 
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     // Set throttling after states are stable. Otherwise it takes too long to reach stable state
-    setSingleThrottlingConfig(StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE,
-        StateTransitionThrottleConfig.ThrottleScope.INSTANCE, 2);
+    setSingleThrottlingConfig(StateTransitionThrottleConfig.RebalanceType.RECOVERY_BALANCE, 2);
 
     DelayedTransition.setDelay(20);
     DelayedTransition.enableThrottleRecord();
@@ -200,8 +198,7 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     // Set ANY type throttling after states are stable.
-    setSingleThrottlingConfig(StateTransitionThrottleConfig.RebalanceType.ANY,
-        StateTransitionThrottleConfig.ThrottleScope.INSTANCE, 1);
+    setSingleThrottlingConfig(StateTransitionThrottleConfig.RebalanceType.ANY, 1);
 
     DelayedTransition.setDelay(20);
     DelayedTransition.enableThrottleRecord();
@@ -229,9 +226,7 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
     Thread.sleep(50);
 
     for (int i = 0; i < _participants.length; i++) {
-      if (_participants[i].isConnected()) {
-        _participants[i].syncStop();
-      }
+      _participants[i].syncStop();
       _participants[i] =
           new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _participants[i].getInstanceName());
     }
@@ -241,7 +236,7 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
   @Test(dependsOnMethods = {
       "testResourceThrottle"
   })
-  public void testResourceThrottleWithDelayRebalancer() throws Exception {
+  public void testResourceThrottleWithDelayRebalancer() {
     // start a few participants
     for (int i = 0; i < NODE_NR - 2; i++) {
       _participants[i].syncStart();
@@ -260,9 +255,7 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
         System.err.println(dbName + "exists!");
         is.setReplicas(String.valueOf(replica));
         is.setMinActiveReplicas(minActiveReplica);
-        if (delay > 0) {
-          is.setRebalanceDelay(delay);
-        }
+        is.setRebalanceDelay(delay);
         is.setRebalancerClassName(DelayedAutoRebalancer.class.getName());
         _gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, dbName, is);
       } else {
@@ -295,31 +288,24 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
       String throttledItemName, int maxPendingTransition) {
     List<PartitionTransitionTime> pTimeList = partitionTransitionTimesMap.get(throttledItemName);
 
-    Map<Long, List<PartitionTransitionTime>> startMap =
-        new HashMap<Long, List<PartitionTransitionTime>>();
-    Map<Long, List<PartitionTransitionTime>> endMap =
-        new HashMap<Long, List<PartitionTransitionTime>>();
-    List<Long> startEndPoints = new ArrayList<Long>();
+    Map<Long, List<PartitionTransitionTime>> startMap = new HashMap<>();
+    Map<Long, List<PartitionTransitionTime>> endMap = new HashMap<>();
+    List<Long> startEndPoints = new ArrayList<>();
 
     if (pTimeList == null) {
       System.out.println("no throttle result for :" + throttledItemName);
       return;
     }
-    Collections.sort(pTimeList, new Comparator<PartitionTransitionTime>() {
-      @Override
-      public int compare(PartitionTransitionTime o1, PartitionTransitionTime o2) {
-        return (int) (o1.start - o2.start);
-      }
-    });
+    pTimeList.sort((o1, o2) -> (int) (o1.start - o2.start));
 
     for (PartitionTransitionTime interval : pTimeList) {
       if (!startMap.containsKey(interval.start)) {
-        startMap.put(interval.start, new ArrayList<PartitionTransitionTime>());
+        startMap.put(interval.start, new ArrayList<>());
       }
       startMap.get(interval.start).add(interval);
 
       if (!endMap.containsKey(interval.end)) {
-        endMap.put(interval.end, new ArrayList<PartitionTransitionTime>());
+        endMap.put(interval.end, new ArrayList<>());
       }
       endMap.get(interval.end).add(interval);
       startEndPoints.add(interval.start);
@@ -328,7 +314,7 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
 
     Collections.sort(startEndPoints);
 
-    List<PartitionTransitionTime> temp = new ArrayList<PartitionTransitionTime>();
+    List<PartitionTransitionTime> temp = new ArrayList<>();
 
     int maxInParallel = 0;
     for (long point : startEndPoints) {
@@ -351,7 +337,7 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
   }
 
   private int size(List<PartitionTransitionTime> timeList) {
-    Set<String> partitions = new HashSet<String>();
+    Set<String> partitions = new HashSet<>();
     for (PartitionTransitionTime p : timeList) {
       partitions.add(p.partition);
     }
@@ -363,7 +349,7 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
     long start;
     long end;
 
-    public PartitionTransitionTime(String partition, long start, long end) {
+    PartitionTransitionTime(String partition, long start, long end) {
       this.partition = partition;
       this.start = start;
       this.end = end;
@@ -371,19 +357,15 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
 
     @Override
     public String toString() {
-      return "[" +
-          "partition='" + partition + '\'' +
-          ", start=" + start +
-          ", end=" + end +
-          ']';
+      return "[" + "partition='" + partition + '\'' + ", start=" + start + ", end=" + end + ']';
     }
   }
 
   private void setSingleThrottlingConfig(StateTransitionThrottleConfig.RebalanceType rebalanceType,
-      StateTransitionThrottleConfig.ThrottleScope scope, int maxStateTransitions) {
+      int maxStateTransitions) {
     ClusterConfig clusterConfig = _configAccessor.getClusterConfig(CLUSTER_NAME);
-    StateTransitionThrottleConfig anyTypeInstanceThrottle =
-        new StateTransitionThrottleConfig(rebalanceType, scope, maxStateTransitions);
+    StateTransitionThrottleConfig anyTypeInstanceThrottle = new StateTransitionThrottleConfig(
+        rebalanceType, StateTransitionThrottleConfig.ThrottleScope.INSTANCE, maxStateTransitions);
     List<StateTransitionThrottleConfig> currentThrottleConfigs =
         clusterConfig.getStateTransitionThrottleConfigs();
     currentThrottleConfigs.add(anyTypeInstanceThrottle);
@@ -393,24 +375,24 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
 
   private static class DelayedTransition extends DelayedTransitionBase {
     private static Map<String, List<PartitionTransitionTime>> resourcePatitionTransitionTimes =
-        new ConcurrentHashMap<String, List<PartitionTransitionTime>>();
+        new ConcurrentHashMap<>();
     private static Map<String, List<PartitionTransitionTime>> instancePatitionTransitionTimes =
-        new ConcurrentHashMap<String, List<PartitionTransitionTime>>();
+        new ConcurrentHashMap<>();
     private static boolean _recordThrottle = false;
 
-    public static Map<String, List<PartitionTransitionTime>> getResourcePatitionTransitionTimes() {
+    static Map<String, List<PartitionTransitionTime>> getResourcePatitionTransitionTimes() {
       return resourcePatitionTransitionTimes;
     }
 
-    public static Map<String, List<PartitionTransitionTime>> getInstancePatitionTransitionTimes() {
+    static Map<String, List<PartitionTransitionTime>> getInstancePatitionTransitionTimes() {
       return instancePatitionTransitionTimes;
     }
 
-    public static void enableThrottleRecord() {
+    static void enableThrottleRecord() {
       _recordThrottle = true;
     }
 
-    public static void clearThrottleRecord() {
+    static void clearThrottleRecord() {
       resourcePatitionTransitionTimes.clear();
       instancePatitionTransitionTimes.clear();
     }
@@ -429,13 +411,13 @@ public class TestPartitionMovementThrottle extends ZkStandAloneCMTestBase {
 
         if (!resourcePatitionTransitionTimes.containsKey(message.getResourceName())) {
           resourcePatitionTransitionTimes.put(message.getResourceName(),
-              Collections.synchronizedList(new ArrayList<PartitionTransitionTime>()));
+              Collections.synchronizedList(new ArrayList<>()));
         }
         resourcePatitionTransitionTimes.get(message.getResourceName()).add(partitionTransitionTime);
 
         if (!instancePatitionTransitionTimes.containsKey(message.getTgtName())) {
           instancePatitionTransitionTimes.put(message.getTgtName(),
-              Collections.synchronizedList(new ArrayList<PartitionTransitionTime>()));
+              Collections.synchronizedList(new ArrayList<>()));
         }
         instancePatitionTransitionTimes.get(message.getTgtName()).add(partitionTransitionTime);
       }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestPauseSignal.java b/helix-core/src/test/java/org/apache/helix/integration/TestPauseSignal.java
index 7e27801..9e15469 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestPauseSignal.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestPauseSignal.java
@@ -22,12 +22,10 @@ package org.apache.helix.integration;
 import java.util.Date;
 import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.TestHelper;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.common.ZkTestBase;
 import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.integration.manager.MockParticipantManager;
 import org.apache.helix.manager.zk.ZKHelixDataAccessor;
-import org.apache.helix.manager.zk.ZNRecordSerializer;
 import org.apache.helix.manager.zk.ZkBaseDataAccessor;
 import org.apache.helix.model.PauseSignal;
 import org.apache.helix.tools.ClusterSetup;
@@ -39,7 +37,6 @@ import org.testng.annotations.Test;
 public class TestPauseSignal extends ZkTestBase {
   @Test()
   public void testPauseSignal() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     final String clusterName = className + "_" + methodName;
@@ -70,14 +67,13 @@ public class TestPauseSignal extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // pause the cluster and make sure pause is persistent
     final HelixDataAccessor tmpAccessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
 
     String cmd = "-zkSvr " + ZK_ADDR + " -enableCluster " + clusterName + " false";
     ClusterSetup.processCommandLineArgs(cmd.split(" "));
@@ -94,18 +90,18 @@ public class TestPauseSignal extends ZkTestBase {
 
     // make sure TestDB1 external view is empty
     TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 1000, clusterName, "TestDB1",
-        TestHelper.<String> setOf("localhost_12918", "localhost_12919", "localhost_12920",
-            "localhost_12921", "localhost_12922"), ZK_ADDR);
+        TestHelper.setOf("localhost_12918", "localhost_12919", "localhost_12920",
+            "localhost_12921", "localhost_12922"),
+        ZK_ADDR);
 
     // resume controller
     final HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
 
     cmd = "-zkSvr " + ZK_ADDR + " -enableCluster " + clusterName + " true";
     ClusterSetup.processCommandLineArgs(cmd.split(" "));
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // clean up
@@ -114,6 +110,7 @@ public class TestPauseSignal extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestPreferenceListAsQueue.java b/helix-core/src/test/java/org/apache/helix/integration/TestPreferenceListAsQueue.java
index 1c005a2..54d9ae6 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestPreferenceListAsQueue.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestPreferenceListAsQueue.java
@@ -21,6 +21,7 @@ package org.apache.helix.integration;
 
 import com.google.common.collect.Lists;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 import java.util.Queue;
 import java.util.concurrent.CountDownLatch;
@@ -51,6 +52,8 @@ import org.apache.helix.tools.ClusterSetup;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
@@ -82,6 +85,11 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
     _clusterSetup.addCluster(_clusterName, true);
   }
 
+  @AfterClass
+  public void afterClass() {
+    deleteCluster(_clusterName);
+  }
+
   /**
    * This test ensures successful creation when the state model has OFFLINE --> deprioritized and
    * a partition-level constraint enforces parallelism
@@ -118,7 +126,7 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
 
     // Add a state model with the parallelism implicit
     _clusterSetup.addStateModelDef(_clusterName, _stateModel,
-        createEnforcedParallelismStateModelDef(_stateModel, PARALLELISM));
+        createEnforcedParallelismStateModelDef(_stateModel));
     runTest();
   }
 
@@ -155,9 +163,8 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
     // Start some instances
     HelixManager[] participants = new HelixManager[NUM_INSTANCES];
     for (int i = 0; i < NUM_INSTANCES; i++) {
-      participants[i] =
-          HelixManagerFactory.getZKHelixManager(_clusterName, instanceInfoArray[i],
-              InstanceType.PARTICIPANT, ZK_ADDR);
+      participants[i] = HelixManagerFactory.getZKHelixManager(_clusterName, instanceInfoArray[i],
+          InstanceType.PARTICIPANT, ZK_ADDR);
       participants[i].getStateMachineEngine().registerStateModelFactory(_stateModel,
           new PrefListTaskOnlineOfflineStateModelFactory());
       participants[i].connect();
@@ -180,19 +187,19 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
 
     // Add one instance
     addInstanceToPreferences(participants[0].getHelixDataAccessor(),
-        participants[0].getInstanceName(), RESOURCE_NAME, Arrays.asList(partitionName));
+        participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
     Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
         Arrays.asList("localhost_1", "")));
 
     // Add a second instance immediately; the first one should still exist
     addInstanceToPreferences(participants[1].getHelixDataAccessor(),
-        participants[1].getInstanceName(), RESOURCE_NAME, Arrays.asList(partitionName));
+        participants[1].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
     Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
         Arrays.asList("localhost_1", "localhost_2")));
 
     // Add the first instance again; it should already exist
     addInstanceToPreferences(participants[0].getHelixDataAccessor(),
-        participants[0].getInstanceName(), RESOURCE_NAME, Arrays.asList(partitionName));
+        participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
     Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
         Arrays.asList("localhost_1", "localhost_2")));
 
@@ -208,6 +215,7 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
     boolean countReached = _onlineLatch.await(10000, TimeUnit.MILLISECONDS);
     Assert.assertTrue(countReached);
     List<String> top = _prefListHistory.poll();
+    assert top != null;
     Assert.assertTrue(top.equals(Arrays.asList("localhost_1", ""))
         || top.equals(Arrays.asList("localhost_2", "")));
     Assert.assertEquals(_prefListHistory.poll(), Arrays.asList("", ""));
@@ -219,9 +227,9 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
     // Add back the instances in the opposite order
     _admin.enableCluster(_clusterName, false);
     addInstanceToPreferences(participants[0].getHelixDataAccessor(),
-        participants[1].getInstanceName(), RESOURCE_NAME, Arrays.asList(partitionName));
+        participants[1].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
     addInstanceToPreferences(participants[0].getHelixDataAccessor(),
-        participants[0].getInstanceName(), RESOURCE_NAME, Arrays.asList(partitionName));
+        participants[0].getInstanceName(), RESOURCE_NAME, Collections.singletonList(partitionName));
     Assert.assertTrue(preferenceListIsCorrect(_admin, _clusterName, RESOURCE_NAME, partitionName,
         Arrays.asList("localhost_2", "localhost_1")));
 
@@ -234,6 +242,7 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
     countReached = _onlineLatch.await(10000, TimeUnit.MILLISECONDS);
     Assert.assertTrue(countReached);
     top = _prefListHistory.poll();
+    assert top != null;
     Assert.assertTrue(top.equals(Arrays.asList("localhost_1", ""))
         || top.equals(Arrays.asList("localhost_2", "")));
     Assert.assertEquals(_prefListHistory.poll(), Arrays.asList("", ""));
@@ -253,13 +262,12 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
    * @return
    */
   private StateModelDefinition createReprioritizedStateModelDef(String stateModelName) {
-    StateModelDefinition.Builder builder =
-        new StateModelDefinition.Builder(stateModelName).addState("ONLINE", 1).addState("OFFLINE")
-            .addState("DROPPED").addState("ERROR").initialState("OFFLINE")
-            .addTransition("ERROR", "OFFLINE", 1).addTransition("ONLINE", "OFFLINE", 2)
-            .addTransition("OFFLINE", "DROPPED", 3).addTransition("OFFLINE", "ONLINE", 4)
-            .dynamicUpperBound("ONLINE", "R").upperBound("OFFLINE", -1).upperBound("DROPPED", -1)
-            .upperBound("ERROR", -1);
+    StateModelDefinition.Builder builder = new StateModelDefinition.Builder(stateModelName)
+        .addState("ONLINE", 1).addState("OFFLINE").addState("DROPPED").addState("ERROR")
+        .initialState("OFFLINE").addTransition("ERROR", "OFFLINE", 1)
+        .addTransition("ONLINE", "OFFLINE", 2).addTransition("OFFLINE", "DROPPED", 3)
+        .addTransition("OFFLINE", "ONLINE", 4).dynamicUpperBound("ONLINE", "R")
+        .upperBound("OFFLINE", -1).upperBound("DROPPED", -1).upperBound("ERROR", -1);
     return builder.build();
   }
 
@@ -267,11 +275,9 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
    * Create a modified version of OnlineOffline where the parallelism is enforced by the upper bound
    * of ONLINE
    * @param stateModelName
-   * @param parallelism
    * @return
    */
-  private StateModelDefinition createEnforcedParallelismStateModelDef(String stateModelName,
-      int parallelism) {
+  private StateModelDefinition createEnforcedParallelismStateModelDef(String stateModelName) {
     StateModelDefinition.Builder builder =
         new StateModelDefinition.Builder(stateModelName).addState("ONLINE", 1).addState("OFFLINE")
             .addState("DROPPED").addState("ERROR").initialState("OFFLINE")
@@ -291,8 +297,8 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
    * @param expectPreferenceList
    * @return
    */
-  private boolean preferenceListIsCorrect(HelixAdmin admin, String clusterName,
-      String resourceName, String partitionName, List<String> expectPreferenceList) {
+  private boolean preferenceListIsCorrect(HelixAdmin admin, String clusterName, String resourceName,
+      String partitionName, List<String> expectPreferenceList) {
     IdealState idealState = admin.getResourceIdealState(clusterName, resourceName);
     List<String> preferenceList = idealState.getPreferenceList(partitionName);
     return expectPreferenceList.equals(preferenceList);
@@ -313,23 +319,21 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
     synchronized (_prefListHistory) {
       // Updater for ideal state
       final List<String> prefList = Lists.newLinkedList();
-      DataUpdater<ZNRecord> idealStateUpdater = new DataUpdater<ZNRecord>() {
-        @Override
-        public ZNRecord update(ZNRecord currentData) {
-          List<String> preferenceList = currentData.getListField(partitionName);
-          int numReplicas =
-              Integer.valueOf(currentData.getSimpleField(IdealStateProperty.REPLICAS.toString()));
-          List<String> newPrefList =
-              removeInstanceFromPreferenceList(preferenceList, instanceName, numReplicas);
-          currentData.setListField(partitionName, newPrefList);
-          prefList.clear();
-          prefList.addAll(newPrefList);
-          return currentData;
-        }
+      DataUpdater<ZNRecord> idealStateUpdater = currentData -> {
+        List<String> preferenceList = currentData.getListField(partitionName);
+        int numReplicas =
+            Integer.valueOf(currentData.getSimpleField(IdealStateProperty.REPLICAS.toString()));
+        List<String> newPrefList =
+            removeInstanceFromPreferenceList(preferenceList, instanceName, numReplicas);
+        currentData.setListField(partitionName, newPrefList);
+        prefList.clear();
+        prefList.addAll(newPrefList);
+        return currentData;
       };
       List<DataUpdater<ZNRecord>> updaters = Lists.newArrayList();
       updaters.add(idealStateUpdater);
-      accessor.updateChildren(Arrays.asList(idealStatePath), updaters, AccessOption.PERSISTENT);
+      accessor.updateChildren(Collections.singletonList(idealStatePath), updaters,
+          AccessOption.PERSISTENT);
       _prefListHistory.add(prefList);
     }
   }
@@ -349,27 +353,25 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
     synchronized (_prefListHistory) {
       // Updater for ideal state
       final List<String> prefList = Lists.newLinkedList();
-      DataUpdater<ZNRecord> idealStateUpdater = new DataUpdater<ZNRecord>() {
-        @Override
-        public ZNRecord update(ZNRecord currentData) {
-          for (String partitionName : partitions) {
-            List<String> preferenceList = currentData.getListField(partitionName);
-            int numReplicas =
-                Integer.valueOf(currentData.getSimpleField(IdealStateProperty.REPLICAS.toString()));
-            List<String> newPrefList =
-                addInstanceToPreferenceList(preferenceList, instanceName, numReplicas);
-            currentData.setListField(partitionName, newPrefList);
-            prefList.clear();
-            prefList.addAll(newPrefList);
-          }
-          return currentData;
+      DataUpdater<ZNRecord> idealStateUpdater = currentData -> {
+        for (String partitionName : partitions) {
+          List<String> preferenceList = currentData.getListField(partitionName);
+          int numReplicas =
+              Integer.valueOf(currentData.getSimpleField(IdealStateProperty.REPLICAS.toString()));
+          List<String> newPrefList =
+              addInstanceToPreferenceList(preferenceList, instanceName, numReplicas);
+          currentData.setListField(partitionName, newPrefList);
+          prefList.clear();
+          prefList.addAll(newPrefList);
         }
+        return currentData;
       };
 
       // Send update requests together
       List<DataUpdater<ZNRecord>> updaters = Lists.newArrayList();
       updaters.add(idealStateUpdater);
-      accessor.updateChildren(Arrays.asList(idealStatePath), updaters, AccessOption.PERSISTENT);
+      accessor.updateChildren(Collections.singletonList(idealStatePath), updaters,
+          AccessOption.PERSISTENT);
       _prefListHistory.add(prefList);
     }
   }
@@ -498,10 +500,11 @@ public class TestPreferenceListAsQueue extends ZkUnitTestBase {
     }
   }
 
-  public class PrefListTaskOnlineOfflineStateModelFactory extends
-      StateModelFactory<PrefListTaskOnlineOfflineStateModel> {
+  public class PrefListTaskOnlineOfflineStateModelFactory
+      extends StateModelFactory<PrefListTaskOnlineOfflineStateModel> {
     @Override
-    public PrefListTaskOnlineOfflineStateModel createNewStateModel(String resource, String partitionName) {
+    public PrefListTaskOnlineOfflineStateModel createNewStateModel(String resource,
+        String partitionName) {
       return new PrefListTaskOnlineOfflineStateModel();
     }
   }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestRebalancerPersistAssignments.java b/helix-core/src/test/java/org/apache/helix/integration/TestRebalancerPersistAssignments.java
index 7deac3d..6f72748 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestRebalancerPersistAssignments.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestRebalancerPersistAssignments.java
@@ -39,12 +39,11 @@ import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
 public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
-  Set<String> _instanceNames = new HashSet<>();
+  private Set<String> _instanceNames = new HashSet<>();
 
   @Override
   @BeforeClass
   public void beforeClass() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
 
     // setup storage cluster
@@ -70,13 +69,18 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
   }
 
   @DataProvider(name = "rebalanceModes")
-  public static Object [][] rebalanceModes() {
-    return new RebalanceMode[][] { {RebalanceMode.SEMI_AUTO}, {RebalanceMode.FULL_AUTO}};
+  public static Object[][] rebalanceModes() {
+    return new RebalanceMode[][] {
+        {
+            RebalanceMode.SEMI_AUTO
+        }, {
+            RebalanceMode.FULL_AUTO
+        }
+    };
   }
 
   @Test(dataProvider = "rebalanceModes")
-  public void testDisablePersist(RebalanceMode rebalanceMode)
-      throws Exception {
+  public void testDisablePersist(RebalanceMode rebalanceMode) {
     String testDb = "TestDB2-" + rebalanceMode.name();
 
     _gSetupTool.addResourceToCluster(CLUSTER_NAME, testDb, 5,
@@ -85,14 +89,14 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
 
     BestPossibleExternalViewVerifier.Builder verifierBuilder =
         new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
-            .setResources(new HashSet<String>(Collections.singleton(testDb)));
+            .setResources(new HashSet<>(Collections.singleton(testDb)));
 
     Assert.assertTrue(verifierBuilder.build().verifyByPolling());
 
     // kill 1 node
     _participants[0].syncStop();
 
-    Set<String> liveInstances = new HashSet<String>(_instanceNames);
+    Set<String> liveInstances = new HashSet<>(_instanceNames);
     liveInstances.remove(_participants[0].getInstanceName());
     verifierBuilder.setExpectLiveInstances(liveInstances);
     Assert.assertTrue(verifierBuilder.build().verifyByPolling());
@@ -100,7 +104,7 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
     IdealState idealState =
         _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
 
-    Set<String> excludedInstances = new HashSet<String>();
+    Set<String> excludedInstances = new HashSet<>();
     excludedInstances.add(_participants[0].getInstanceName());
     verifyAssignmentInIdealStateWithPersistDisabled(idealState, excludedInstances);
 
@@ -111,9 +115,10 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
     _participants[0].syncStart();
   }
 
-  @Test(dataProvider = "rebalanceModes", dependsOnMethods = {"testDisablePersist"})
-  public void testEnablePersist(RebalanceMode rebalanceMode)
-      throws Exception {
+  @Test(dataProvider = "rebalanceModes", dependsOnMethods = {
+      "testDisablePersist"
+  })
+  public void testEnablePersist(RebalanceMode rebalanceMode) {
     String testDb = "TestDB1-" + rebalanceMode.name();
     enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
 
@@ -123,18 +128,18 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
 
     BestPossibleExternalViewVerifier.Builder verifierBuilder =
         new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
-            .setResources(new HashSet<String>(Collections.singleton(testDb)));
+            .setResources(new HashSet<>(Collections.singleton(testDb)));
 
     Assert.assertTrue(verifierBuilder.build().verifyByPolling());
 
     IdealState idealState =
         _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
-    verifyAssignmentInIdealStateWithPersistEnabled(idealState, new HashSet<String>());
+    verifyAssignmentInIdealStateWithPersistEnabled(idealState, new HashSet<>());
 
     // kill 1 node
     _participants[0].syncStop();
 
-    Set<String> liveInstances = new HashSet<String>(_instanceNames);
+    Set<String> liveInstances = new HashSet<>(_instanceNames);
     liveInstances.remove(_participants[0].getInstanceName());
     verifierBuilder.setExpectLiveInstances(liveInstances);
     Assert.assertTrue(verifierBuilder.build().verifyByPolling());
@@ -142,7 +147,7 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
     idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
     // verify that IdealState contains updated assignment in it map fields.
 
-    Set<String> excludedInstances = new HashSet<String>();
+    Set<String> excludedInstances = new HashSet<>();
     excludedInstances.add(_participants[0].getInstanceName());
     verifyAssignmentInIdealStateWithPersistEnabled(idealState, excludedInstances);
 
@@ -154,12 +159,13 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
   }
 
   /**
-   * This test is to test the temporary solution for solving Espresso/Databus back-compatible map format issue.
-   *
-   * @throws Exception
+   * This test is to test the temporary solution for solving Espresso/Databus back-compatible map
+   * format issue.
    */
-  @Test(dependsOnMethods = { "testDisablePersist" })
-  public void testSemiAutoEnablePersistMasterSlave() throws Exception {
+  @Test(dependsOnMethods = {
+      "testDisablePersist"
+  })
+  public void testSemiAutoEnablePersistMasterSlave() {
     String testDb = "TestDB1-MasterSlave";
     enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
 
@@ -169,7 +175,7 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
 
     BestPossibleExternalViewVerifier.Builder verifierBuilder =
         new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
-            .setResources(new HashSet<String>(Collections.singleton(testDb)));
+            .setResources(new HashSet<>(Collections.singleton(testDb)));
 
     Assert.assertTrue(verifierBuilder.build().verifyByPolling());
 
@@ -180,7 +186,7 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
     // kill 1 node
     _participants[0].syncStop();
 
-    Set<String> liveInstances = new HashSet<String>(_instanceNames);
+    Set<String> liveInstances = new HashSet<>(_instanceNames);
     liveInstances.remove(_participants[0].getInstanceName());
     verifierBuilder.setExpectLiveInstances(liveInstances);
     Assert.assertTrue(verifierBuilder.build().verifyByPolling());
@@ -189,15 +195,15 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
     verifySemiAutoMasterSlaveAssignment(idealState);
 
     // disable an instance
-    _gSetupTool.getClusterManagementTool()
-        .enableInstance(CLUSTER_NAME, _participants[1].getInstanceName(), false);
+    _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
+        _participants[1].getInstanceName(), false);
     idealState = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, testDb);
     verifySemiAutoMasterSlaveAssignment(idealState);
 
     // clean up
     _gSetupTool.getClusterManagementTool().dropResource(CLUSTER_NAME, testDb);
-    _gSetupTool.getClusterManagementTool()
-        .enableInstance(CLUSTER_NAME, _participants[1].getInstanceName(), true);
+    _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME,
+        _participants[1].getInstanceName(), true);
     _participants[0].reset();
     _participants[0].syncStart();
   }
@@ -212,8 +218,8 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
         Assert.assertTrue(instanceStateMap.containsKey(ins),
             String.format("Instance %s from preference list not in the map", ins));
         String state = instanceStateMap.get(ins);
-        Assert.assertTrue(state.equals(MasterSlaveSMD.States.MASTER.name()) || state
-            .equals(MasterSlaveSMD.States.SLAVE.name()), "Actual State" + state);
+        Assert.assertTrue(state.equals(MasterSlaveSMD.States.MASTER.name())
+            || state.equals(MasterSlaveSMD.States.SLAVE.name()), "Actual State" + state);
         if (state.equals(MasterSlaveSMD.States.MASTER.name())) {
           numMaster++;
         }
@@ -238,7 +244,7 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
         Assert.assertTrue(instanceInList.containsAll(instancesInMap));
       }
 
-      if(idealState.getRebalanceMode() == RebalanceMode.FULL_AUTO) {
+      if (idealState.getRebalanceMode() == RebalanceMode.FULL_AUTO) {
         // preference list should be persisted in IS.
         List<String> instanceList = idealState.getPreferenceList(partition);
         Assert.assertNotNull(instanceList);
@@ -267,11 +273,11 @@ public class TestRebalancerPersistAssignments extends ZkStandAloneCMTestBase {
       mapFieldEmpty = false;
       Set<String> instancesInMap = instanceStateMap.keySet();
       for (String ins : excludedInstances) {
-        if(instancesInMap.contains(ins)) {
+        if (instancesInMap.contains(ins)) {
           // if at least one excluded instance is included, it means assignment was not updated.
           assignmentNotChanged = true;
         }
-        if(idealState.getRebalanceMode() == RebalanceMode.FULL_AUTO) {
+        if (idealState.getRebalanceMode() == RebalanceMode.FULL_AUTO) {
           List<String> instanceList = idealState.getPreferenceList(partition);
           if (instanceList.contains(ins)) {
             assignmentNotChanged = true;
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestReelectedPipelineCorrectness.java b/helix-core/src/test/java/org/apache/helix/integration/TestReelectedPipelineCorrectness.java
index 11f1e0a..7343785 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestReelectedPipelineCorrectness.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestReelectedPipelineCorrectness.java
@@ -157,7 +157,7 @@ public class TestReelectedPipelineCorrectness extends ZkUnitTestBase {
       participants[i].syncStop();
     }
     TestHelper.dropCluster(clusterName, _gZkClient);
-
+    deleteCluster(controllerCluster);
     System.out.println("STOP " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestRenamePartition.java b/helix-core/src/test/java/org/apache/helix/integration/TestRenamePartition.java
index 6d63cc1..3c0194b 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestRenamePartition.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestRenamePartition.java
@@ -41,12 +41,10 @@ import org.testng.annotations.Test;
 
 public class TestRenamePartition extends ZkTestBase {
   // map from clusterName to participants
-  final Map<String, MockParticipantManager[]> _participantMap =
-      new ConcurrentHashMap<String, MockParticipantManager[]>();
+  private final Map<String, MockParticipantManager[]> _participantMap = new ConcurrentHashMap<>();
 
   // map from clusterName to controllers
-  final Map<String, ClusterControllerManager> _controllerMap =
-      new ConcurrentHashMap<String, ClusterControllerManager>();
+  private final Map<String, ClusterControllerManager> _controllerMap = new ConcurrentHashMap<>();
 
   @Test()
   public void testRenamePartitionAutoIS() throws Exception {
@@ -66,7 +64,7 @@ public class TestRenamePartition extends ZkTestBase {
 
     // rename partition name TestDB0_0 tp TestDB0_100
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     Builder keyBuilder = accessor.keyBuilder();
 
     IdealState idealState = accessor.getProperty(keyBuilder.idealStates("TestDB0"));
@@ -75,9 +73,8 @@ public class TestRenamePartition extends ZkTestBase {
     idealState.getRecord().getListFields().put("TestDB0_100", prioList);
     accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
 
-    boolean result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    boolean result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     stop(clusterName);
@@ -100,19 +97,17 @@ public class TestRenamePartition extends ZkTestBase {
         "MasterSlave", false); // do rebalance
 
     // calculate idealState
-    List<String> instanceNames =
-        Arrays.asList("localhost_12918", "localhost_12919", "localhost_12920", "localhost_12921",
-            "localhost_12922");
-    ZNRecord destIS =
-        DefaultIdealStateCalculator.calculateIdealState(instanceNames, 10, 3 - 1, "TestDB0",
-            "MASTER", "SLAVE");
+    List<String> instanceNames = Arrays.asList("localhost_12918", "localhost_12919",
+        "localhost_12920", "localhost_12921", "localhost_12922");
+    ZNRecord destIS = DefaultIdealStateCalculator.calculateIdealState(instanceNames, 10, 3 - 1,
+        "TestDB0", "MASTER", "SLAVE");
     IdealState idealState = new IdealState(destIS);
     idealState.setRebalanceMode(RebalanceMode.CUSTOMIZED);
     idealState.setReplicas("3");
     idealState.setStateModelDefRef("MasterSlave");
 
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     Builder keyBuilder = accessor.keyBuilder();
 
     accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
@@ -123,17 +118,15 @@ public class TestRenamePartition extends ZkTestBase {
     idealState.getRecord().getMapFields().put("TestDB0_100", stateMap);
     accessor.setProperty(keyBuilder.idealStates("TestDB0"), idealState);
 
-    boolean result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    boolean result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     stop(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
-
   }
 
-  private void startAndVerify(String clusterName) throws Exception {
+  private void startAndVerify(String clusterName) {
     MockParticipantManager[] participants = new MockParticipantManager[5];
 
     ClusterControllerManager controller =
@@ -148,9 +141,8 @@ public class TestRenamePartition extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    boolean result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     _participantMap.put(clusterName, participants);
@@ -169,5 +161,7 @@ public class TestRenamePartition extends ZkTestBase {
         participant.syncStop();
       }
     }
+
+    deleteCluster(clusterName);
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestResetInstance.java b/helix-core/src/test/java/org/apache/helix/integration/TestResetInstance.java
index 354a185..48fa742 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestResetInstance.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestResetInstance.java
@@ -107,6 +107,7 @@ public class TestResetInstance extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
   }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestSchemataSM.java b/helix-core/src/test/java/org/apache/helix/integration/TestSchemataSM.java
index aa65939..4dd7191 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestSchemataSM.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestSchemataSM.java
@@ -19,12 +19,11 @@ package org.apache.helix.integration;
  * under the License.
  */
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Date;
 import java.util.Map;
 import org.apache.helix.PropertyKey;
 import org.apache.helix.TestHelper;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.common.ZkTestBase;
 import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.integration.manager.MockParticipantManager;
@@ -60,13 +59,13 @@ public class TestSchemataSM extends ZkTestBase {
 
     // rebalance ideal-state to use ANY_LIVEINSTANCE for preference list
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     PropertyKey key = keyBuilder.idealStates("TestSchemata0");
     IdealState idealState = accessor.getProperty(key);
     idealState.setReplicas(IdealState.IdealStateConstants.ANY_LIVEINSTANCE.toString());
     idealState.getRecord().setListField("TestSchemata0_0",
-        Arrays.asList(IdealState.IdealStateConstants.ANY_LIVEINSTANCE.toString()));
+        Collections.singletonList(IdealState.IdealStateConstants.ANY_LIVEINSTANCE.toString()));
     accessor.setProperty(key, idealState);
 
     ClusterControllerManager controller =
@@ -81,9 +80,8 @@ public class TestSchemataSM extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // start the remaining 1 participant
@@ -91,9 +89,8 @@ public class TestSchemataSM extends ZkTestBase {
     participants[0].syncStart();
 
     // make sure we have all participants in MASTER state
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
     key = keyBuilder.externalView("TestSchemata0");
     ExternalView externalView = accessor.getProperty(key);
@@ -112,6 +109,7 @@ public class TestSchemataSM extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestSessionExpiryInTransition.java b/helix-core/src/test/java/org/apache/helix/integration/TestSessionExpiryInTransition.java
index 285927a..abc61e1 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestSessionExpiryInTransition.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestSessionExpiryInTransition.java
@@ -50,7 +50,7 @@ public class TestSessionExpiryInTransition extends ZkTestBase {
       String partition = message.getPartitionName();
       if (instance.equals("localhost_12918") && partition.equals("TestDB0_1") // TestDB0_1 is SLAVE
                                                                               // on localhost_12918
-          && _done.getAndSet(true) == false) {
+          && !_done.getAndSet(true)) {
         try {
           ZkTestHelper.expireSession(manager.getZkClient());
         } catch (Exception e) {
@@ -62,8 +62,6 @@ public class TestSessionExpiryInTransition extends ZkTestBase {
 
   @Test
   public void testSessionExpiryInTransition() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.WARN);
-
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     final String clusterName = className + "_" + methodName;
@@ -94,9 +92,8 @@ public class TestSessionExpiryInTransition extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // clean up
@@ -105,7 +102,7 @@ public class TestSessionExpiryInTransition extends ZkTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
-
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMMain.java b/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMMain.java
index 0e8b7a1..ff208ce 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMMain.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMMain.java
@@ -20,11 +20,11 @@ package org.apache.helix.integration;
  */
 
 import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
 import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.PropertyKey;
 import org.apache.helix.TestHelper;
-import org.apache.helix.TestHelper.Verifier;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
 import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.manager.zk.ZKHelixDataAccessor;
@@ -42,40 +42,41 @@ public class TestStandAloneCMMain extends ZkStandAloneCMTestBase {
   @Test()
   public void testStandAloneCMMain() throws Exception {
     logger.info("RUN testStandAloneCMMain() at " + new Date(System.currentTimeMillis()));
+
+    // Keep references to the controllers created so that they could be shut down
+    Set<ClusterControllerManager> controllers = new HashSet<>();
+
     ClusterControllerManager newController = null;
     for (int i = 1; i <= 2; i++) {
       String controllerName = "controller_" + i;
-      newController =
-          new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
+      newController = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
       newController.syncStart();
+      controllers.add(newController);
     }
 
-    // stopCurrentLeader(_zkClient, CLUSTER_NAME, _startCMResultMap);
     _controller.syncStop();
 
     final HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<>(_gZkClient));
     final PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     final String newControllerName = newController.getInstanceName();
-    TestHelper.verify(new Verifier() {
-
-      @Override
-      public boolean verify() throws Exception {
-        LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
-        if (leader == null) {
-          return false;
-        }
-        return leader.getInstanceName().equals(newControllerName);
-
+    TestHelper.verify(() -> {
+      LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
+      if (leader == null) {
+        return false;
       }
+      return leader.getInstanceName().equals(newControllerName);
+
     }, 30 * 1000);
 
-    boolean result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, CLUSTER_NAME));
-    Assert.assertTrue(result);
+    Assert.assertTrue(ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, CLUSTER_NAME)));
+
+    // Shut down all controllers so that the cluster could be deleted
+    for (ClusterControllerManager controller : controllers) {
+      controller.syncStop();
+    }
 
     logger.info("STOP testStandAloneCMMain() at " + new Date(System.currentTimeMillis()));
   }
-
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMSessionExpiry.java b/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMSessionExpiry.java
index 89fbfe8..d9532c2 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMSessionExpiry.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestStandAloneCMSessionExpiry.java
@@ -27,17 +27,12 @@ import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.integration.manager.MockParticipantManager;
 import org.apache.helix.tools.ClusterSetup;
 import org.apache.helix.tools.ClusterStateVerifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
 public class TestStandAloneCMSessionExpiry extends ZkTestBase {
-  private static Logger LOG = LoggerFactory.getLogger(TestStandAloneCMSessionExpiry.class);
-
   @Test()
   public void testStandAloneCMSessionExpiry() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.DEBUG);
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     String clusterName = className + "_" + methodName;
@@ -59,20 +54,19 @@ public class TestStandAloneCMSessionExpiry extends ZkTestBase {
     controller.syncStart();
 
     boolean result;
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // participant session expiry
     MockParticipantManager participantToExpire = participants[1];
 
-    System.out.println("Expire participant session");
+    // System.out.println("Expire participant session");
     String oldSessionId = participantToExpire.getSessionId();
 
     ZkTestHelper.expireSession(participantToExpire.getZkClient());
     String newSessionId = participantToExpire.getSessionId();
-    System.out.println("oldSessionId: " + oldSessionId + ", newSessionId: " + newSessionId);
+    // System.out.println("oldSessionId: " + oldSessionId + ", newSessionId: " + newSessionId);
     Assert.assertTrue(newSessionId.compareTo(oldSessionId) > 0,
         "Session id should be increased after expiry");
 
@@ -80,38 +74,34 @@ public class TestStandAloneCMSessionExpiry extends ZkTestBase {
     setupTool.addResourceToCluster(clusterName, "TestDB1", 10, "MasterSlave");
     setupTool.rebalanceStorageCluster(clusterName, "TestDB1", 3);
 
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // controller session expiry
-    System.out.println("Expire controller session");
+    // System.out.println("Expire controller session");
     oldSessionId = controller.getSessionId();
     ZkTestHelper.expireSession(controller.getZkClient());
     newSessionId = controller.getSessionId();
-    System.out.println("oldSessionId: " + oldSessionId + ", newSessionId: " + newSessionId);
+    // System.out.println("oldSessionId: " + oldSessionId + ", newSessionId: " + newSessionId);
     Assert.assertTrue(newSessionId.compareTo(oldSessionId) > 0,
         "Session id should be increased after expiry");
 
     setupTool.addResourceToCluster(clusterName, "TestDB2", 8, "MasterSlave");
     setupTool.rebalanceStorageCluster(clusterName, "TestDB2", 3);
 
-    result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // clean up
     System.out.println("Clean up ...");
-    // Logger.getRootLogger().setLevel(Level.DEBUG);
     controller.syncStop();
     for (int i = 0; i < 5; i++) {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
-
   }
-
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestStateTransitionThrottle.java b/helix-core/src/test/java/org/apache/helix/integration/TestStateTransitionThrottle.java
index 861eee0..f1628f6 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestStateTransitionThrottle.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestStateTransitionThrottle.java
@@ -29,7 +29,6 @@ import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.NotificationContext;
 import org.apache.helix.PropertyKey;
 import org.apache.helix.TestHelper;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.api.config.StateTransitionThrottleConfig;
 import org.apache.helix.common.ZkTestBase;
 import org.apache.helix.integration.manager.ClusterControllerManager;
@@ -47,9 +46,8 @@ import org.testng.Assert;
 import org.testng.annotations.Test;
 
 public class TestStateTransitionThrottle extends ZkTestBase {
-  int participantCount = 4;
+  private int participantCount = 4;
   String resourceName = "TestDB0";
-  String resourceNamePrefix = "TestDB";
 
   @Test
   public void testTransitionThrottleOnRecoveryPartition() throws Exception {
@@ -59,7 +57,7 @@ public class TestStateTransitionThrottle extends ZkTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     final ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     setupCluster(clusterName, accessor);
 
     // start partial participants
@@ -123,7 +121,7 @@ public class TestStateTransitionThrottle extends ZkTestBase {
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
 
     final ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     setupCluster(clusterName, accessor);
 
     // Set throttle config to enable throttling
@@ -191,6 +189,7 @@ public class TestStateTransitionThrottle extends ZkTestBase {
   }
 
   private void setupCluster(String clusterName, ZKHelixDataAccessor accessor) throws Exception {
+    String resourceNamePrefix = "TestDB";
     TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant start port
         "localhost", // participant name prefix
         resourceNamePrefix, // resource name prefix
@@ -218,15 +217,12 @@ public class TestStateTransitionThrottle extends ZkTestBase {
   private static boolean pollForPartitionAssignment(final HelixDataAccessor accessor,
       final MockParticipantManager participant, final String resourceName, final int timeout)
       throws Exception {
-    return TestHelper.verify(new TestHelper.Verifier() {
-      @Override
-      public boolean verify() throws Exception {
-        PropertyKey.Builder keyBuilder = accessor.keyBuilder();
-        PropertyKey partitionStatusKey = keyBuilder.currentState(participant.getInstanceName(),
-            participant.getSessionId(), resourceName);
-        CurrentState currentState = accessor.getProperty(partitionStatusKey);
-        return currentState != null && !currentState.getPartitionStateMap().isEmpty();
-      }
+    return TestHelper.verify(() -> {
+      PropertyKey.Builder keyBuilder = accessor.keyBuilder();
+      PropertyKey partitionStatusKey = keyBuilder.currentState(participant.getInstanceName(),
+          participant.getSessionId(), resourceName);
+      CurrentState currentState = accessor.getProperty(partitionStatusKey);
+      return currentState != null && !currentState.getPartitionStateMap().isEmpty();
     }, timeout);
   }
 }
\ No newline at end of file
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestSyncSessionToController.java b/helix-core/src/test/java/org/apache/helix/integration/TestSyncSessionToController.java
index 2960b6e..5d34a1c 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestSyncSessionToController.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestSyncSessionToController.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.Date;
 import java.util.List;
 import org.apache.helix.InstanceType;
@@ -18,11 +37,11 @@ import org.apache.zookeeper.data.Stat;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
-
 public class TestSyncSessionToController extends ZkTestBase {
   @Test
   public void testSyncSessionToController() throws Exception {
-    System.out.println("START testSyncSessionToController at " + new Date(System.currentTimeMillis()));
+    System.out
+        .println("START testSyncSessionToController at " + new Date(System.currentTimeMillis()));
 
     String clusterName = getShortClassName();
     MockParticipantManager[] participants = new MockParticipantManager[5];
@@ -43,41 +62,49 @@ public class TestSyncSessionToController extends ZkTestBase {
     // start participants
     for (int i = 0; i < 5; i++) {
       String instanceName = "localhost_" + (12918 + i);
-
       participants[i] = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
       participants[i].syncStart();
     }
 
-    ZKHelixManager zkHelixManager = new ZKHelixManager(clusterName, "controllerMessageListener", InstanceType.CONTROLLER, ZK_ADDR);
+    ZKHelixManager zkHelixManager = new ZKHelixManager(clusterName, "controllerMessageListener",
+        InstanceType.CONTROLLER, ZK_ADDR);
     zkHelixManager.connect();
     MockMessageListener mockMessageListener = new MockMessageListener();
     zkHelixManager.addControllerMessageListener(mockMessageListener);
 
     PropertyKey.Builder keyBuilder = new PropertyKey.Builder(clusterName);
-    ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient);
+    ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<>(_gZkClient);
     String path = keyBuilder.liveInstance("localhost_12918").getPath();
     Stat stat = new Stat();
     ZNRecord data = accessor.get(path, stat, 2);
     data.getSimpleFields().put("SESSION_ID", "invalid-id");
     accessor.set(path, data, 2);
     Thread.sleep(2000);
-
     Assert.assertTrue(mockMessageListener.isSessionSyncMessageSent());
+
+    // Cleanup
+    controller.syncStop();
+    zkHelixManager.disconnect();
+    for (int i = 0; i < 5; i++) {
+      participants[i].syncStop();
+    }
+    deleteCluster(clusterName);
   }
 
   class MockMessageListener implements MessageListener {
     private boolean sessionSyncMessageSent = false;
 
     @Override
-    public void onMessage(String instanceName, List<Message> messages, NotificationContext changeContext) {
-      for (Message message: messages) {
+    public void onMessage(String instanceName, List<Message> messages,
+        NotificationContext changeContext) {
+      for (Message message : messages) {
         if (message.getMsgId().equals("SESSION-SYNC")) {
           sessionSyncMessageSent = true;
         }
       }
     }
 
-    public boolean isSessionSyncMessageSent() {
+    boolean isSessionSyncMessageSent() {
       return sessionSyncMessageSent;
     }
   }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestWeightBasedRebalanceUtil.java b/helix-core/src/test/java/org/apache/helix/integration/TestWeightBasedRebalanceUtil.java
index 95a3f8a..5a5a252 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestWeightBasedRebalanceUtil.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestWeightBasedRebalanceUtil.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Date;
@@ -28,8 +47,6 @@ import org.apache.helix.model.OnlineOfflineSMD;
 import org.apache.helix.model.Partition;
 import org.apache.helix.model.ResourceConfig;
 import org.apache.helix.util.WeightAwareRebalanceUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
@@ -38,7 +55,6 @@ import org.testng.annotations.Test;
 import static org.apache.helix.controller.rebalancer.constraint.dataprovider.ZkBasedPartitionWeightProvider.DEFAULT_WEIGHT_VALUE;
 
 public class TestWeightBasedRebalanceUtil extends ZkTestBase {
-  private static Logger _logger = LoggerFactory.getLogger(TestWeightBasedRebalanceUtil.class);
   private static String CLUSTER_NAME;
 
   final String resourceNamePrefix = "resource";
@@ -180,13 +196,14 @@ public class TestWeightBasedRebalanceUtil extends ZkTestBase {
 
     WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
     ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(resourceConfigs, null,
-        Collections.<AbstractRebalanceHardConstraint>singletonList(capacityConstraint),
-        Collections.<AbstractRebalanceSoftConstraint>singletonList(evenConstraint));
+        Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
+        Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
     Map<String, Integer> weightCount = checkPartitionUsage(assignment, weightProvider);
 
     int max = Collections.max(weightCount.values());
     int min = Collections.min(weightCount.values());
-    // Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of participant capacity in max.
+    // Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of
+    // participant capacity in max.
     Assert.assertTrue((max - min) <= defaultCapacity / 100);
   }
 
@@ -195,10 +212,10 @@ public class TestWeightBasedRebalanceUtil extends ZkTestBase {
     Map<String, Integer> resourceDefaultWeightMap = new HashMap<>();
     resourceDefaultWeightMap.put(resourceNames.get(0), resourceWeight * 2);
     Map<String, Map<String, Integer>> partitionWeightMap = new HashMap<>();
-    partitionWeightMap
-        .put(resourceNames.get(0), Collections.singletonMap(partitions.get(0), resourceWeight * 3));
-    partitionWeightMap
-        .put(resourceNames.get(1), Collections.singletonMap(partitions.get(0), resourceWeight * 3));
+    partitionWeightMap.put(resourceNames.get(0),
+        Collections.singletonMap(partitions.get(0), resourceWeight * 3));
+    partitionWeightMap.put(resourceNames.get(1),
+        Collections.singletonMap(partitions.get(0), resourceWeight * 3));
 
     ZkBasedPartitionWeightProvider weightProvider =
         new ZkBasedPartitionWeightProvider(ZK_ADDR, CLUSTER_NAME, "Test");
@@ -300,13 +317,14 @@ public class TestWeightBasedRebalanceUtil extends ZkTestBase {
 
     WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
     ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(resourceConfigs, null,
-        Collections.<AbstractRebalanceHardConstraint>singletonList(capacityConstraint),
-        Collections.<AbstractRebalanceSoftConstraint>singletonList(evenConstraint));
+        Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
+        Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
     Map<String, Integer> weightCount = checkPartitionUsage(assignment, weightProvider);
 
     int max = Collections.max(weightCount.values());
     int min = Collections.min(weightCount.values());
-    // Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of participant capacity in max.
+    // Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of
+    // participant capacity in max.
     Assert.assertTrue((max - min) <= defaultCapacity / 100);
   }
 
@@ -338,14 +356,14 @@ public class TestWeightBasedRebalanceUtil extends ZkTestBase {
 
     WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
     ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(resourceConfigs, null,
-        Collections.<AbstractRebalanceHardConstraint>singletonList(hardConstraint),
-        Collections.<AbstractRebalanceSoftConstraint>singletonList(evenConstraint));
+        Collections.<AbstractRebalanceHardConstraint> singletonList(hardConstraint),
+        Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
     Map<String, Integer> weightCount = checkPartitionUsage(assignment, weightProvider);
 
     for (int i = 0; i < instanceNames.size(); i++) {
       String instance = instanceNames.get(i);
       if (i % 7 == 0) {
-        Assert.assertTrue(!weightCount.containsKey(instance));
+        Assert.assertFalse(weightCount.containsKey(instance));
       } else {
         Assert.assertTrue(weightCount.get(instance) > 0);
       }
@@ -376,40 +394,38 @@ public class TestWeightBasedRebalanceUtil extends ZkTestBase {
     String targetResource = resourceNames.get(0);
     for (String partition : partitions) {
       for (int i = 0; i < nReplicas; i++) {
-        existingAssignment
-            .setState(targetResource, new Partition(partition), instanceNames.get(i), topState);
+        existingAssignment.setState(targetResource, new Partition(partition), instanceNames.get(i),
+            topState);
       }
     }
 
     WeightAwareRebalanceUtil util = new WeightAwareRebalanceUtil(clusterConfig, instanceConfigs);
 
     // INCREMENTAL
-    ResourcesStateMap assignment =
-        util.buildIncrementalRebalanceAssignment(resourceConfigs, existingAssignment,
-            Collections.EMPTY_LIST,
-            Collections.<AbstractRebalanceSoftConstraint>singletonList(evenConstraint));
+    ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(resourceConfigs,
+        existingAssignment, Collections.EMPTY_LIST,
+        Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
     // check if the existingAssignment is changed
     for (String partition : partitions) {
-      Assert.assertTrue(
-          assignment.getInstanceStateMap(targetResource, new Partition(partition)).keySet()
-              .containsAll(instanceNames.subList(0, nReplicas)));
+      Assert.assertTrue(assignment.getInstanceStateMap(targetResource, new Partition(partition))
+          .keySet().containsAll(instanceNames.subList(0, nReplicas)));
     }
     // still need to check for balance
     Map<String, Integer> weightCount = checkPartitionUsage(assignment, weightProvider);
     int max = Collections.max(weightCount.values());
     int min = Collections.min(weightCount.values());
-    // Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of participant capacity in max.
+    // Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of
+    // participant capacity in max.
     Assert.assertTrue((max - min) <= defaultCapacity / 100);
 
     // FULL
     assignment = util.buildFullRebalanceAssignment(resourceConfigs, existingAssignment,
         Collections.EMPTY_LIST,
-        Collections.<AbstractRebalanceSoftConstraint>singletonList(evenConstraint));
+        Collections.<AbstractRebalanceSoftConstraint> singletonList(evenConstraint));
     // check if the existingAssignment is changed
     for (String partition : partitions) {
-      Assert.assertFalse(
-          assignment.getInstanceStateMap(targetResource, new Partition(partition)).keySet()
-              .containsAll(instanceNames.subList(0, nReplicas)));
+      Assert.assertFalse(assignment.getInstanceStateMap(targetResource, new Partition(partition))
+          .keySet().containsAll(instanceNames.subList(0, nReplicas)));
     }
   }
 
@@ -459,7 +475,7 @@ public class TestWeightBasedRebalanceUtil extends ZkTestBase {
           .setRebalanceMode(RebalanceConfig.RebalanceMode.FULL_AUTO);
       util.buildIncrementalRebalanceAssignment(
           Collections.singletonList(invalidResourceBuilder.build()), null,
-          Collections.<AbstractRebalanceHardConstraint>singletonList(capacityConstraint),
+          Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
           Collections.EMPTY_LIST);
       Assert.fail("Should fail due to full auto resource config.");
     } catch (HelixException ex) {
@@ -473,7 +489,7 @@ public class TestWeightBasedRebalanceUtil extends ZkTestBase {
       invalidResourceBuilder.setStateModelDefRef("CustomizedOnlineOffline");
       util.buildIncrementalRebalanceAssignment(
           Collections.singletonList(invalidResourceBuilder.build()), null,
-          Collections.<AbstractRebalanceHardConstraint>singletonList(capacityConstraint),
+          Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
           Collections.EMPTY_LIST);
       Assert.fail("Should fail due to unknown state model def ref.");
     } catch (IllegalArgumentException ex) {
@@ -481,7 +497,7 @@ public class TestWeightBasedRebalanceUtil extends ZkTestBase {
       util.registerCustomizedStateModelDef("CustomizedOnlineOffline", OnlineOfflineSMD.build());
       ResourcesStateMap assignment = util.buildIncrementalRebalanceAssignment(
           Collections.singletonList(invalidResourceBuilder.build()), null,
-          Collections.<AbstractRebalanceHardConstraint>singletonList(capacityConstraint),
+          Collections.<AbstractRebalanceHardConstraint> singletonList(capacityConstraint),
           Collections.EMPTY_LIST);
       checkPartitionUsage(assignment, weightProvider);
     }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestZkConnectionLost.java b/helix-core/src/test/java/org/apache/helix/integration/TestZkConnectionLost.java
index 8473180..595468a 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestZkConnectionLost.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestZkConnectionLost.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.ExecutionException;
@@ -41,8 +60,8 @@ public class TestZkConnectionLost extends TaskTestBase {
   private final AtomicReference<ZkServer> _zkServerRef = new AtomicReference<>();
 
   private String _zkAddr = "localhost:21893";
-  ClusterSetup _setupTool;
-  HelixZkClient _zkClient;
+  private ClusterSetup _setupTool;
+  private HelixZkClient _zkClient;
 
   @BeforeClass
   public void beforeClass() throws Exception {
@@ -77,9 +96,7 @@ public class TestZkConnectionLost extends TaskTestBase {
       _manager.disconnect();
     }
     stopParticipants();
-
     TestHelper.dropCluster(CLUSTER_NAME, _zkClient, _setupTool);
-
     _zkClient.close();
     TestHelper.stopZkServer(_zkServerRef.get());
   }
@@ -111,7 +128,9 @@ public class TestZkConnectionLost extends TaskTestBase {
     }
   }
 
-  @Test(dependsOnMethods = { "testLostZkConnection" }, enabled = false)
+  @Test(dependsOnMethods = {
+      "testLostZkConnection"
+  }, enabled = false)
   public void testLostZkConnectionNegative() throws Exception {
     System.setProperty(SystemPropertyKeys.ZK_WAIT_CONNECTED_TIMEOUT, "10");
     System.setProperty(SystemPropertyKeys.ZK_SESSION_TIMEOUT, "1000");
@@ -138,7 +157,7 @@ public class TestZkConnectionLost extends TaskTestBase {
         _driver.pollForWorkflowState(scheduledQueue, 30000, TaskState.COMPLETED);
         Assert.fail("Test failure!");
       } catch (HelixException ex) {
-        // test succeed
+        // test succeeded
       }
     } finally {
       System.clearProperty(SystemPropertyKeys.ZK_WAIT_CONNECTED_TIMEOUT);
@@ -149,33 +168,30 @@ public class TestZkConnectionLost extends TaskTestBase {
   private void restartZkServer() throws ExecutionException, InterruptedException {
     // shutdown and restart zk for a couple of times
     for (int i = 0; i < 4; i++) {
-      Executors.newSingleThreadExecutor().submit(new Runnable() {
-        @Override public void run() {
-          try {
-            Thread.sleep(300);
-            System.out.println(System.currentTimeMillis() + ": Shutdown ZK server.");
-            TestHelper.stopZkServer(_zkServerRef.get());
-            Thread.sleep(300);
-            System.out.println("Restart ZK server");
-            _zkServerRef.set(TestHelper.startZkServer(_zkAddr, null, false));
-          } catch (Exception e) {
-            LOG.error(e.getMessage(), e);
-          }
+      Executors.newSingleThreadExecutor().submit(() -> {
+        try {
+          Thread.sleep(300);
+          System.out.println(System.currentTimeMillis() + ": Shutdown ZK server.");
+          TestHelper.stopZkServer(_zkServerRef.get());
+          Thread.sleep(300);
+          System.out.println("Restart ZK server");
+          _zkServerRef.set(TestHelper.startZkServer(_zkAddr, null, false));
+        } catch (Exception e) {
+          LOG.error(e.getMessage(), e);
         }
       }).get();
     }
   }
 
   private List<String> createAndEnqueueJob(JobQueue.Builder queueBuild, int jobCount) {
-    List<String> currentJobNames = new ArrayList<String>();
+    List<String> currentJobNames = new ArrayList<>();
     for (int i = 0; i < jobCount; i++) {
       String targetPartition = (i == 0) ? "MASTER" : "SLAVE";
 
-      JobConfig.Builder jobConfig =
-          new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND)
-              .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
-              .setTargetPartitionStates(Sets.newHashSet(targetPartition))
-              .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100"));
+      JobConfig.Builder jobConfig = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND)
+          .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
+          .setTargetPartitionStates(Sets.newHashSet(targetPartition))
+          .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100"));
       String jobName = targetPartition.toLowerCase() + "Job" + i;
       queueBuild.enqueueJob(jobName, jobConfig);
       currentJobNames.add(jobName);
@@ -184,5 +200,3 @@ public class TestZkConnectionLost extends TaskTestBase {
     return currentJobNames;
   }
 }
-
-
diff --git a/helix-core/src/test/java/org/apache/helix/integration/TestZkSessionExpiry.java b/helix-core/src/test/java/org/apache/helix/integration/TestZkSessionExpiry.java
index 411f656..79451f1 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/TestZkSessionExpiry.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/TestZkSessionExpiry.java
@@ -43,19 +43,18 @@ import org.testng.Assert;
 import org.testng.annotations.Test;
 
 public class TestZkSessionExpiry extends ZkUnitTestBase {
-  final static String DUMMY_MSG_TYPE = "DUMMY";
+  private final static String DUMMY_MSG_TYPE = "DUMMY";
 
   static class DummyMessageHandler extends MessageHandler {
     final Set<String> _handledMsgSet;
 
-    public DummyMessageHandler(Message message, NotificationContext context,
-        Set<String> handledMsgSet) {
+    DummyMessageHandler(Message message, NotificationContext context, Set<String> handledMsgSet) {
       super(message, context);
       _handledMsgSet = handledMsgSet;
     }
 
     @Override
-    public HelixTaskResult handleMessage() throws InterruptedException {
+    public HelixTaskResult handleMessage() {
       _handledMsgSet.add(_message.getId());
       HelixTaskResult ret = new HelixTaskResult();
       ret.setSuccess(true);
@@ -72,7 +71,7 @@ public class TestZkSessionExpiry extends ZkUnitTestBase {
   static class DummyMessageHandlerFactory implements MultiTypeMessageHandlerFactory {
     final Set<String> _handledMsgSet;
 
-    public DummyMessageHandlerFactory(Set<String> handledMsgSet) {
+    DummyMessageHandlerFactory(Set<String> handledMsgSet) {
       _handledMsgSet = handledMsgSet;
     }
 
@@ -86,7 +85,8 @@ public class TestZkSessionExpiry extends ZkUnitTestBase {
       return DUMMY_MSG_TYPE;
     }
 
-    @Override public List<String> getMessageTypes() {
+    @Override
+    public List<String> getMessageTypes() {
       return ImmutableList.of(DUMMY_MSG_TYPE);
     }
 
@@ -120,7 +120,7 @@ public class TestZkSessionExpiry extends ZkUnitTestBase {
     controller.syncStart();
 
     // start participants
-    Set<String> handledMsgSet = new HashSet<String>();
+    Set<String> handledMsgSet = new HashSet<>();
     MockParticipantManager[] participants = new MockParticipantManager[n];
     for (int i = 0; i < n; i++) {
       String instanceName = "localhost_" + (12918 + i);
@@ -131,10 +131,8 @@ public class TestZkSessionExpiry extends ZkUnitTestBase {
       participants[i].syncStart();
     }
 
-    boolean result =
-        ClusterStateVerifier
-            .verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
-                clusterName));
+    boolean result = ClusterStateVerifier.verifyByZkCallback(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // trigger dummy message handler
@@ -142,10 +140,8 @@ public class TestZkSessionExpiry extends ZkUnitTestBase {
 
     // expire localhost_12918
     ZkTestHelper.expireSession(participants[0].getZkClient());
-    result =
-        ClusterStateVerifier
-            .verifyByZkCallback(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR,
-                clusterName));
+    result = ClusterStateVerifier.verifyByZkCallback(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // trigger dummy message handler again
@@ -157,6 +153,7 @@ public class TestZkSessionExpiry extends ZkUnitTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -166,21 +163,14 @@ public class TestZkSessionExpiry extends ZkUnitTestBase {
    * @param handledMsgSet
    * @throws Exception
    */
-  private static void checkDummyMsgHandler(HelixManager manager,
-      final Set<String> handledMsgSet) throws Exception {
+  private static void checkDummyMsgHandler(HelixManager manager, final Set<String> handledMsgSet)
+      throws Exception {
 
     final Message aMsg = newMsg();
     HelixDataAccessor accessor = manager.getHelixDataAccessor();
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     accessor.setProperty(keyBuilder.message(manager.getInstanceName(), aMsg.getId()), aMsg);
-    boolean result = TestHelper.verify(new TestHelper.Verifier() {
-
-      @Override
-      public boolean verify() throws Exception {
-
-        return handledMsgSet.contains(aMsg.getId());
-      }
-    }, 5 * 1000);
+    boolean result = TestHelper.verify(() -> handledMsgSet.contains(aMsg.getId()), 5 * 1000);
     Assert.assertTrue(result);
   }
 
diff --git a/helix-core/src/test/java/org/apache/helix/integration/common/ZkStandAloneCMTestBase.java b/helix-core/src/test/java/org/apache/helix/integration/common/ZkStandAloneCMTestBase.java
index cfc6ffd..24ad03f 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/common/ZkStandAloneCMTestBase.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/common/ZkStandAloneCMTestBase.java
@@ -40,8 +40,6 @@ import org.testng.annotations.BeforeClass;
  */
 
 public class ZkStandAloneCMTestBase extends ZkTestBase {
-  private static Logger LOG = LoggerFactory.getLogger(ZkStandAloneCMTestBase.class);
-
   protected static final int NODE_NR = 5;
   protected static final int START_PORT = 12918;
   protected static final String STATE_MODEL = "MasterSlave";
@@ -60,7 +58,7 @@ public class ZkStandAloneCMTestBase extends ZkTestBase {
 
   @BeforeClass
   public void beforeClass() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
+    super.beforeClass();
     System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
 
     // setup storage cluster
@@ -95,7 +93,7 @@ public class ZkStandAloneCMTestBase extends ZkTestBase {
 
   @AfterClass
   public void afterClass() throws Exception {
-    /**
+    /*
      * shutdown order: 1) disconnect the controller 2) disconnect participants
      */
     if (_controller != null && _controller.isConnected()) {
diff --git a/helix-core/src/test/java/org/apache/helix/integration/controller/TestClusterMaintenanceMode.java b/helix-core/src/test/java/org/apache/helix/integration/controller/TestClusterMaintenanceMode.java
index 2e4f440..c8b5004 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/controller/TestClusterMaintenanceMode.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/controller/TestClusterMaintenanceMode.java
@@ -68,29 +68,30 @@ public class TestClusterMaintenanceMode extends TaskTestBase {
 
   @Test
   public void testNotInMaintenanceMode() {
-    boolean isInMaintenanceMode = _gSetupTool.getClusterManagementTool().isInMaintenanceMode(CLUSTER_NAME);
+    boolean isInMaintenanceMode =
+        _gSetupTool.getClusterManagementTool().isInMaintenanceMode(CLUSTER_NAME);
     Assert.assertFalse(isInMaintenanceMode);
   }
 
-  @Test (dependsOnMethods = "testNotInMaintenanceMode")
+  @Test(dependsOnMethods = "testNotInMaintenanceMode")
   public void testInMaintenanceMode() {
     _gSetupTool.getClusterManagementTool().enableMaintenanceMode(CLUSTER_NAME, true, "Test");
-    boolean isInMaintenanceMode = _gSetupTool.getClusterManagementTool().isInMaintenanceMode(CLUSTER_NAME);
+    boolean isInMaintenanceMode =
+        _gSetupTool.getClusterManagementTool().isInMaintenanceMode(CLUSTER_NAME);
     Assert.assertTrue(isInMaintenanceMode);
   }
 
-  @Test (dependsOnMethods = "testInMaintenanceMode")
-  public void testMaintenanceModeAddNewInstance() throws InterruptedException {
+  @Test(dependsOnMethods = "testInMaintenanceMode")
+  public void testMaintenanceModeAddNewInstance() {
     _gSetupTool.getClusterManagementTool().enableMaintenanceMode(CLUSTER_NAME, true, "Test");
     ExternalView prevExternalView = _gSetupTool.getClusterManagementTool()
         .getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
     String instanceName = PARTICIPANT_PREFIX + "_" + (_startPort + 10);
     _gSetupTool.addInstanceToCluster(CLUSTER_NAME, instanceName);
-    _newInstance =
-        new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
+    _newInstance = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
     _newInstance.syncStart();
-    _gSetupTool.getClusterManagementTool()
-        .rebalance(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, 3);
+    _gSetupTool.getClusterManagementTool().rebalance(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB,
+        3);
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
     ExternalView newExternalView = _gSetupTool.getClusterManagementTool()
         .getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
@@ -98,21 +99,21 @@ public class TestClusterMaintenanceMode extends TaskTestBase {
         newExternalView.getRecord().getMapFields());
   }
 
-  @Test (dependsOnMethods = "testMaintenanceModeAddNewInstance")
-  public void testMaintenanceModeAddNewResource() throws InterruptedException {
-    _gSetupTool.getClusterManagementTool()
-        .addResource(CLUSTER_NAME, newResourceAddedDuringMaintenanceMode, 7, "MasterSlave",
-            IdealState.RebalanceMode.FULL_AUTO.name());
-    _gSetupTool.getClusterManagementTool()
-        .rebalance(CLUSTER_NAME, newResourceAddedDuringMaintenanceMode, 3);
+  @Test(dependsOnMethods = "testMaintenanceModeAddNewInstance")
+  public void testMaintenanceModeAddNewResource() {
+    _gSetupTool.getClusterManagementTool().addResource(CLUSTER_NAME,
+        newResourceAddedDuringMaintenanceMode, 7, "MasterSlave",
+        IdealState.RebalanceMode.FULL_AUTO.name());
+    _gSetupTool.getClusterManagementTool().rebalance(CLUSTER_NAME,
+        newResourceAddedDuringMaintenanceMode, 3);
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
     ExternalView externalView = _gSetupTool.getClusterManagementTool()
         .getResourceExternalView(CLUSTER_NAME, newResourceAddedDuringMaintenanceMode);
     Assert.assertNull(externalView);
   }
 
-  @Test (dependsOnMethods = "testMaintenanceModeAddNewResource")
-  public void testMaintenanceModeInstanceDown() throws InterruptedException {
+  @Test(dependsOnMethods = "testMaintenanceModeAddNewResource")
+  public void testMaintenanceModeInstanceDown() {
     _participants[0].syncStop();
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
     ExternalView externalView = _gSetupTool.getClusterManagementTool()
@@ -122,8 +123,8 @@ public class TestClusterMaintenanceMode extends TaskTestBase {
     }
   }
 
-  @Test (dependsOnMethods = "testMaintenanceModeInstanceDown")
-  public void testMaintenanceModeInstanceBack() throws InterruptedException {
+  @Test(dependsOnMethods = "testMaintenanceModeInstanceDown")
+  public void testMaintenanceModeInstanceBack() {
     _participants[0] =
         new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, _participants[0].getInstanceName());
     _participants[0].syncStart();
@@ -132,13 +133,13 @@ public class TestClusterMaintenanceMode extends TaskTestBase {
         .getResourceExternalView(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
     for (Map<String, String> stateMap : externalView.getRecord().getMapFields().values()) {
       if (stateMap.containsKey(_participants[0].getInstanceName())) {
-        Assert.assertTrue(stateMap.get(_participants[0].getInstanceName()).equals("SLAVE"));
+        Assert.assertEquals(stateMap.get(_participants[0].getInstanceName()), "SLAVE");
       }
     }
   }
 
-  @Test (dependsOnMethods = "testMaintenanceModeInstanceBack")
-  public void testExitMaintenanceModeNewResourceRecovery() throws InterruptedException {
+  @Test(dependsOnMethods = "testMaintenanceModeInstanceBack")
+  public void testExitMaintenanceModeNewResourceRecovery() {
     _gSetupTool.getClusterManagementTool().enableMaintenanceMode(CLUSTER_NAME, false);
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
     ExternalView externalView = _gSetupTool.getClusterManagementTool()
@@ -186,7 +187,8 @@ public class TestClusterMaintenanceMode extends TaskTestBase {
   @Test(dependsOnMethods = "testAutoExitMaintenanceMode")
   public void testNoAutoExitWhenManuallyPutInMaintenance() throws InterruptedException {
     // Manually put the cluster in maintenance
-    _gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, true, null, null);
+    _gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, true, null,
+        null);
 
     // Kill 2 instances, which makes it a total of 3 down instances
     for (int i = 0; i < 2; i++) {
@@ -214,7 +216,8 @@ public class TestClusterMaintenanceMode extends TaskTestBase {
   @Test(dependsOnMethods = "testNoAutoExitWhenManuallyPutInMaintenance")
   public void testManualEnablingOverridesAutoEnabling() throws InterruptedException {
     // Exit maintenance mode manually
-    _gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, false, null, null);
+    _gSetupTool.getClusterManagementTool().manuallyEnableMaintenanceMode(CLUSTER_NAME, false, null,
+        null);
 
     // Kill 3 instances, which would put cluster in maintenance automatically
     for (int i = 0; i < 3; i++) {
diff --git a/helix-core/src/test/java/org/apache/helix/integration/controller/TestControllerLeadershipChange.java b/helix-core/src/test/java/org/apache/helix/integration/controller/TestControllerLeadershipChange.java
index f497894..5eaa083 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/controller/TestControllerLeadershipChange.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/controller/TestControllerLeadershipChange.java
@@ -65,9 +65,8 @@ public class TestControllerLeadershipChange extends ZkTestBase {
     participant.syncStart();
 
     // Create controller, since this is the only controller, it will be the leader
-    HelixManager manager1 = HelixManagerFactory
-        .getZKHelixManager(clusterName, clusterName + "-manager1", InstanceType.CONTROLLER,
-            ZK_ADDR);
+    HelixManager manager1 = HelixManagerFactory.getZKHelixManager(clusterName,
+        clusterName + "-manager1", InstanceType.CONTROLLER, ZK_ADDR);
     manager1.connect();
     Assert.assertTrue(manager1.isLeader());
 
@@ -76,8 +75,7 @@ public class TestControllerLeadershipChange extends ZkTestBase {
         IdealState.RebalanceMode.SEMI_AUTO.name());
 
     // Rebalance Resource
-    _gSetupTool
-        .rebalanceResource(clusterName, resourceName, numReplica);
+    _gSetupTool.rebalanceResource(clusterName, resourceName, numReplica);
 
     // Wait for rebalance
     Assert.assertTrue(clusterVerifier.verifyByPolling());
@@ -88,9 +86,8 @@ public class TestControllerLeadershipChange extends ZkTestBase {
     Thread.sleep(1000);
 
     // Starting manager2
-    HelixManager manager2 = HelixManagerFactory
-        .getZKHelixManager(clusterName, clusterName + "-manager2", InstanceType.CONTROLLER,
-            ZK_ADDR);
+    HelixManager manager2 = HelixManagerFactory.getZKHelixManager(clusterName,
+        clusterName + "-manager2", InstanceType.CONTROLLER, ZK_ADDR);
     manager2.connect();
 
     // Set leader to manager2
@@ -112,7 +109,6 @@ public class TestControllerLeadershipChange extends ZkTestBase {
     participant = new MockParticipantManager(ZK_ADDR, clusterName, instanceName);
     participant.syncStart();
 
-
     _gSetupTool.rebalanceResource(clusterName, resourceName, numReplica);
 
     Assert.assertTrue(clusterVerifier.verifyByPolling());
@@ -120,9 +116,13 @@ public class TestControllerLeadershipChange extends ZkTestBase {
     // Resource lost top state, and manager1 lost leadership for 2000ms, because manager1 will
     // clean monitoring cache after re-gaining leadership, so max value of hand off duration should
     // not have such a large value
-    Assert.assertTrue((long) beanServer
-        .getAttribute(resourceMBeanObjectName, "PartitionTopStateHandoffDurationGauge.Max") < 500);
+    Assert.assertTrue((long) beanServer.getAttribute(resourceMBeanObjectName,
+        "PartitionTopStateHandoffDurationGauge.Max") < 500);
 
+    participant.syncStop();
+    manager1.disconnect();
+    manager2.disconnect();
+    deleteCluster(clusterName);
   }
 
   private void setLeader(HelixManager manager) throws Exception {
@@ -135,17 +135,15 @@ public class TestControllerLeadershipChange extends ZkTestBase {
 
     // Delete the current controller leader node so it will trigger leader election
     while (!manager.isLeader()) {
-      accessor.getBaseDataAccessor()
-          .remove(PropertyPathBuilder.controllerLeader(manager.getClusterName()), AccessOption.EPHEMERAL);
+      accessor.getBaseDataAccessor().remove(
+          PropertyPathBuilder.controllerLeader(manager.getClusterName()), AccessOption.EPHEMERAL);
       Thread.sleep(50);
     }
   }
 
   private ObjectName getResourceMonitorObjectName(String clusterName, String resourceName)
       throws Exception {
-    return new ObjectName(String
-        .format("%s:cluster=%s,resourceName=%s", MonitorDomainNames.ClusterStatus.name(),
-            clusterName, resourceName));
+    return new ObjectName(String.format("%s:cluster=%s,resourceName=%s",
+        MonitorDomainNames.ClusterStatus.name(), clusterName, resourceName));
   }
-
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/manager/TestConsecutiveZkSessionExpiry.java b/helix-core/src/test/java/org/apache/helix/integration/manager/TestConsecutiveZkSessionExpiry.java
index 391bdd5..f8fa101 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/manager/TestConsecutiveZkSessionExpiry.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/manager/TestConsecutiveZkSessionExpiry.java
@@ -79,7 +79,6 @@ public class TestConsecutiveZkSessionExpiry extends ZkUnitTestBase {
 
   @Test
   public void testParticipant() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     String clusterName = className + "_" + methodName;
@@ -156,6 +155,7 @@ public class TestConsecutiveZkSessionExpiry extends ZkUnitTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -257,6 +257,7 @@ public class TestConsecutiveZkSessionExpiry extends ZkUnitTestBase {
     Assert.assertNull(pollForProperty(LiveInstance.class, accessor, keyBuilder.controllerLeader(),
         false));
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
diff --git a/helix-core/src/test/java/org/apache/helix/integration/manager/TestControllerManager.java b/helix-core/src/test/java/org/apache/helix/integration/manager/TestControllerManager.java
index a7f7a7b..a4af04b 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/manager/TestControllerManager.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/manager/TestControllerManager.java
@@ -92,6 +92,7 @@ public class TestControllerManager extends ZkUnitTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -154,7 +155,7 @@ public class TestControllerManager extends ZkUnitTestBase {
       participants[i].syncStop();
     }
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
-
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/manager/TestDistributedControllerManager.java b/helix-core/src/test/java/org/apache/helix/integration/manager/TestDistributedControllerManager.java
index 909e44c..6c1e0eb 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/manager/TestDistributedControllerManager.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/manager/TestDistributedControllerManager.java
@@ -25,7 +25,6 @@ import org.apache.helix.HelixManager;
 import org.apache.helix.InstanceType;
 import org.apache.helix.PropertyKey;
 import org.apache.helix.TestHelper;
-import org.apache.helix.ZNRecord;
 import org.apache.helix.ZkTestHelper;
 import org.apache.helix.common.ZkTestBase;
 import org.apache.helix.manager.zk.CallbackHandler;
@@ -46,7 +45,6 @@ public class TestDistributedControllerManager extends ZkTestBase {
 
   @Test
   public void simpleIntegrationTest() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     String clusterName = className + "_" + methodName;
@@ -66,17 +64,15 @@ public class TestDistributedControllerManager extends ZkTestBase {
     HelixManager[] distributedControllers = new HelixManager[n];
     for (int i = 0; i < n; i++) {
       int port = 12918 + i;
-      distributedControllers[i] =
-          new ZKHelixManager(clusterName, "localhost_" + port, InstanceType.CONTROLLER_PARTICIPANT,
-              ZK_ADDR);
+      distributedControllers[i] = new ZKHelixManager(clusterName, "localhost_" + port,
+          InstanceType.CONTROLLER_PARTICIPANT, ZK_ADDR);
       distributedControllers[i].getStateMachineEngine().registerStateModelFactory("MasterSlave",
           new MockMSModelFactory());
       distributedControllers[i].connect();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // disconnect first distributed-controller, and verify second takes leadership
@@ -84,13 +80,12 @@ public class TestDistributedControllerManager extends ZkTestBase {
 
     // verify leader changes to localhost_12919
     Thread.sleep(100);
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
     Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance("localhost_12918")));
     LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
@@ -102,6 +97,7 @@ public class TestDistributedControllerManager extends ZkTestBase {
     Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance("localhost_12919")));
     Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader()));
 
+    deleteCluster(clusterName);
     System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -111,11 +107,11 @@ public class TestDistributedControllerManager extends ZkTestBase {
    * @param newController
    * @throws Exception
    */
-  void expireController(ClusterDistributedController expireController,
+  private void expireController(ClusterDistributedController expireController,
       ClusterDistributedController newController) throws Exception {
     String clusterName = expireController.getClusterName();
-    LOG.info("Expiring distributedController: " + expireController.getInstanceName()
-        + ", session: " + expireController.getSessionId() + " ...");
+    LOG.info("Expiring distributedController: " + expireController.getInstanceName() + ", session: "
+        + expireController.getSessionId() + " ...");
     String oldSessionId = expireController.getSessionId();
 
     ZkTestHelper.expireSession(expireController.getZkClient());
@@ -123,17 +119,16 @@ public class TestDistributedControllerManager extends ZkTestBase {
     LOG.debug("Expired distributedController: " + expireController.getInstanceName()
         + ", oldSessionId: " + oldSessionId + ", newSessionId: " + newSessionId);
 
-    boolean result =
-        ClusterStateVerifier.verifyByPolling(new ClusterStateVerifier.BestPossAndExtViewZkVerifier(
-            ZK_ADDR, clusterName));
+    boolean result = ClusterStateVerifier.verifyByPolling(
+        new ClusterStateVerifier.BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // verify leader changes to localhost_12919
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
-    Assert.assertNotNull(accessor.getProperty(keyBuilder.liveInstance(expireController
-        .getInstanceName())));
+    Assert.assertNotNull(
+        accessor.getProperty(keyBuilder.liveInstance(expireController.getInstanceName())));
     LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader());
     Assert.assertNotNull(leader);
     Assert.assertEquals(leader.getId(), newController.getInstanceName());
@@ -143,17 +138,13 @@ public class TestDistributedControllerManager extends ZkTestBase {
         + TestHelper.printHandlers(expireController));
 
     List<CallbackHandler> handlers = expireController.getHandlers();
-    Assert
-        .assertEquals(
-            handlers.size(),
-            1,
-            "Distributed controller should have 1 handler (message) after lose leadership, but was "
-                + handlers.size());
+    Assert.assertEquals(handlers.size(), 1,
+        "Distributed controller should have 1 handler (message) after lose leadership, but was "
+            + handlers.size());
   }
 
   @Test
   public void simpleSessionExpiryTest() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     String className = TestHelper.getTestClassName();
     String methodName = TestHelper.getTestMethodName();
     String clusterName = className + "_" + methodName;
@@ -181,9 +172,8 @@ public class TestDistributedControllerManager extends ZkTestBase {
       distributedControllers[i].connect();
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
     Assert.assertTrue(result);
 
     // expire localhost_12918
@@ -194,16 +184,17 @@ public class TestDistributedControllerManager extends ZkTestBase {
 
     // clean up
     ZKHelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<>(_gZkClient));
     PropertyKey.Builder keyBuilder = accessor.keyBuilder();
 
     for (int i = 0; i < n; i++) {
       distributedControllers[i].disconnect();
-      Assert.assertNull(accessor.getProperty(keyBuilder.liveInstance(distributedControllers[i]
-          .getInstanceName())));
+      Assert.assertNull(accessor
+          .getProperty(keyBuilder.liveInstance(distributedControllers[i].getInstanceName())));
     }
     Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader()));
 
+    deleteCluster(clusterName);
     System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/manager/TestHelixDataAccessor.java b/helix-core/src/test/java/org/apache/helix/integration/manager/TestHelixDataAccessor.java
index a8ccc50..a6882d4 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/manager/TestHelixDataAccessor.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/manager/TestHelixDataAccessor.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration.manager;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -16,20 +35,20 @@ import org.apache.helix.manager.zk.ZKHelixDataAccessor;
 import org.apache.helix.manager.zk.ZkBaseDataAccessor;
 import org.apache.helix.mock.MockZkClient;
 import org.testng.Assert;
+import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 public class TestHelixDataAccessor extends ZkTestBase {
   private MockZkClient _zkClient;
-  BaseDataAccessor<ZNRecord> baseDataAccessor;
-  HelixDataAccessor accessor;
-  List<PropertyKey> propertyKeys;
+  private HelixDataAccessor accessor;
+  private List<PropertyKey> propertyKeys;
 
   @BeforeClass
   public void beforeClass() {
     _zkClient = new MockZkClient(ZK_ADDR);
 
-    baseDataAccessor = new ZkBaseDataAccessor<>(_zkClient);
+    BaseDataAccessor<ZNRecord> baseDataAccessor = new ZkBaseDataAccessor<>(_zkClient);
     accessor = new ZKHelixDataAccessor("HELIX", baseDataAccessor);
 
     Map<String, HelixProperty> paths = new TreeMap<>();
@@ -49,13 +68,18 @@ public class TestHelixDataAccessor extends ZkTestBase {
     _zkClient.putData(key.getPath(), null);
   }
 
+  @AfterClass
+  public void afterClass() {
+    _zkClient.deleteRecursively("/HELIX");
+  }
+
   @Test
   public void testHelixDataAccessorReadData() {
     accessor.getProperty(new ArrayList<>(propertyKeys), false);
     try {
       accessor.getProperty(new ArrayList<>(propertyKeys), true);
       Assert.fail();
-    } catch (HelixMetaDataAccessException ex) {
+    } catch (HelixMetaDataAccessException ignored) {
     }
 
     PropertyKey idealStates = accessor.keyBuilder().idealStates();
@@ -63,18 +87,20 @@ public class TestHelixDataAccessor extends ZkTestBase {
     try {
       accessor.getChildValues(idealStates, true);
       Assert.fail();
-    } catch (HelixMetaDataAccessException ex) {
+    } catch (HelixMetaDataAccessException ignored) {
     }
 
     accessor.getChildValuesMap(idealStates, false);
     try {
       accessor.getChildValuesMap(idealStates, true);
       Assert.fail();
-    } catch (HelixMetaDataAccessException ex) {
+    } catch (HelixMetaDataAccessException ignored) {
     }
   }
 
-  @Test (expectedExceptions = {HelixMetaDataAccessException.class})
+  @Test(expectedExceptions = {
+      HelixMetaDataAccessException.class
+  })
   public void testDataProviderRefresh() {
     ResourceControllerDataProvider cache = new ResourceControllerDataProvider("MyCluster");
     cache.refresh(accessor);
diff --git a/helix-core/src/test/java/org/apache/helix/integration/manager/TestParticipantManager.java b/helix-core/src/test/java/org/apache/helix/integration/manager/TestParticipantManager.java
index 565bb4d..3999bd2 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/manager/TestParticipantManager.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/manager/TestParticipantManager.java
@@ -19,17 +19,16 @@ package org.apache.helix.integration.manager;
  * under the License.
  */
 
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectInstance;
-import javax.management.ObjectName;
 import java.lang.management.ManagementFactory;
 import java.lang.reflect.Method;
 import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
-
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectInstance;
+import javax.management.ObjectName;
 import org.apache.helix.HelixManager;
 import org.apache.helix.InstanceType;
 import org.apache.helix.NotificationContext;
@@ -51,22 +50,17 @@ import org.apache.helix.monitoring.mbeans.HelixCallbackMonitor;
 import org.apache.helix.monitoring.mbeans.MBeanRegistrar;
 import org.apache.helix.monitoring.mbeans.MonitorDomainNames;
 import org.apache.helix.monitoring.mbeans.MonitorLevel;
-import org.apache.helix.monitoring.mbeans.ThreadPoolExecutorMonitor;
 import org.apache.helix.monitoring.mbeans.ZkClientMonitor;
 import org.apache.helix.monitoring.mbeans.ZkClientPathMonitor;
-import org.apache.helix.tools.ClusterStateVerifier;
-import org.apache.helix.tools.ClusterStateVerifier.BestPossAndExtViewZkVerifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
 import org.testng.Assert;
 import org.testng.ITestContext;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.Test;
 
 public class TestParticipantManager extends ZkTestBase {
-  private static Logger LOG = LoggerFactory.getLogger(TestParticipantManager.class);
-  MBeanServer _server = ManagementFactory.getPlatformMBeanServer();
-  String clusterName = TestHelper.getTestClassName();
+  private MBeanServer _server = ManagementFactory.getPlatformMBeanServer();
+  private String clusterName = TestHelper.getTestClassName();
 
   @AfterMethod
   public void afterMethod(Method testMethod, ITestContext testContext) {
@@ -89,20 +83,23 @@ public class TestParticipantManager extends ZkTestBase {
 
     HelixManager participant =
         new ZKHelixManager(clusterName, "localhost_12918", InstanceType.PARTICIPANT, ZK_ADDR);
-    participant.getStateMachineEngine()
-        .registerStateModelFactory("MasterSlave", new MockMSModelFactory());
+    participant.getStateMachineEngine().registerStateModelFactory("MasterSlave",
+        new MockMSModelFactory());
     participant.connect();
 
     HelixManager controller =
         new ZKHelixManager(clusterName, "controller_0", InstanceType.CONTROLLER, ZK_ADDR);
     controller.connect();
 
-    verifyHelixManagerMetrics(InstanceType.PARTICIPANT, MonitorLevel.DEFAULT, participant.getInstanceName());
-    verifyHelixManagerMetrics(InstanceType.CONTROLLER, MonitorLevel.DEFAULT, controller.getInstanceName());
+    verifyHelixManagerMetrics(InstanceType.PARTICIPANT, MonitorLevel.DEFAULT,
+        participant.getInstanceName());
+    verifyHelixManagerMetrics(InstanceType.CONTROLLER, MonitorLevel.DEFAULT,
+        controller.getInstanceName());
 
-    boolean result = ClusterStateVerifier
-        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
-    Assert.assertTrue(result);
+    BestPossibleExternalViewVerifier verifier =
+        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
+            .setZkAddr(ZK_ADDR).build();
+    Assert.assertTrue(verifier.verifyByPolling());
 
     // cleanup
     controller.disconnect();
@@ -116,7 +113,7 @@ public class TestParticipantManager extends ZkTestBase {
     Assert.assertNull(accessor.getProperty(keyBuilder.controllerLeader()));
   }
 
-  @Test//(dependsOnMethods = "simpleIntegrationTest")
+  @Test // (dependsOnMethods = "simpleIntegrationTest")
   public void testMonitoringLevel() throws Exception {
     int n = 1;
     TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, // participant port
@@ -137,18 +134,19 @@ public class TestParticipantManager extends ZkTestBase {
       System.clearProperty(SystemPropertyKeys.MONITOR_LEVEL);
     }
 
-    participant.getStateMachineEngine()
-        .registerStateModelFactory("MasterSlave", new MockMSModelFactory());
+    participant.getStateMachineEngine().registerStateModelFactory("MasterSlave",
+        new MockMSModelFactory());
     participant.connect();
 
-    verifyHelixManagerMetrics(InstanceType.PARTICIPANT, MonitorLevel.ALL, participant.getInstanceName());
+    verifyHelixManagerMetrics(InstanceType.PARTICIPANT, MonitorLevel.ALL,
+        participant.getInstanceName());
 
     // cleanup
     participant.disconnect();
   }
 
-  private void verifyHelixManagerMetrics(InstanceType type, MonitorLevel monitorLevel, String instanceName)
-      throws MalformedObjectNameException {
+  private void verifyHelixManagerMetrics(InstanceType type, MonitorLevel monitorLevel,
+      String instanceName) throws MalformedObjectNameException {
     // check HelixCallback Monitor
     Set<ObjectInstance> objs =
         _server.queryMBeans(buildCallbackMonitorObjectName(type, clusterName, instanceName), null);
@@ -159,8 +157,8 @@ public class TestParticipantManager extends ZkTestBase {
         _server.queryMBeans(buildZkClientMonitorObjectName(type, clusterName, instanceName), null);
     Assert.assertEquals(objs.size(), 1);
 
-    objs = _server
-        .queryMBeans(buildZkClientPathMonitorObjectName(type, clusterName, instanceName), null);
+    objs = _server.queryMBeans(buildZkClientPathMonitorObjectName(type, clusterName, instanceName),
+        null);
 
     int expectedZkPathMonitor;
     switch (monitorLevel) {
@@ -179,30 +177,27 @@ public class TestParticipantManager extends ZkTestBase {
 
   private ObjectName buildCallbackMonitorObjectName(InstanceType type, String cluster,
       String instance) throws MalformedObjectNameException {
-    return MBeanRegistrar
-        .buildObjectName(MonitorDomainNames.HelixCallback.name(), HelixCallbackMonitor.MONITOR_TYPE,
-            type.name(), HelixCallbackMonitor.MONITOR_KEY, cluster + "." + instance,
-            HelixCallbackMonitor.MONITOR_CHANGE_TYPE, "*");
+    return MBeanRegistrar.buildObjectName(MonitorDomainNames.HelixCallback.name(),
+        HelixCallbackMonitor.MONITOR_TYPE, type.name(), HelixCallbackMonitor.MONITOR_KEY,
+        cluster + "." + instance, HelixCallbackMonitor.MONITOR_CHANGE_TYPE, "*");
   }
 
   private ObjectName buildZkClientMonitorObjectName(InstanceType type, String cluster,
       String instance) throws MalformedObjectNameException {
-    return MBeanRegistrar
-        .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE,
-            type.name(), ZkClientMonitor.MONITOR_KEY, cluster + "." + instance);
+    return MBeanRegistrar.buildObjectName(MonitorDomainNames.HelixZkClient.name(),
+        ZkClientMonitor.MONITOR_TYPE, type.name(), ZkClientMonitor.MONITOR_KEY,
+        cluster + "." + instance);
   }
 
   private ObjectName buildZkClientPathMonitorObjectName(InstanceType type, String cluster,
       String instance) throws MalformedObjectNameException {
-    return MBeanRegistrar
-        .buildObjectName(MonitorDomainNames.HelixZkClient.name(), ZkClientMonitor.MONITOR_TYPE,
-            type.name(), ZkClientMonitor.MONITOR_KEY, cluster + "." + instance,
-            ZkClientPathMonitor.MONITOR_PATH, "*");
+    return MBeanRegistrar.buildObjectName(MonitorDomainNames.HelixZkClient.name(),
+        ZkClientMonitor.MONITOR_TYPE, type.name(), ZkClientMonitor.MONITOR_KEY,
+        cluster + "." + instance, ZkClientPathMonitor.MONITOR_PATH, "*");
   }
 
   @Test
   public void simpleSessionExpiryTest() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.WARN);
     int n = 1;
 
     MockParticipantManager[] participants = new MockParticipantManager[n];
@@ -228,9 +223,10 @@ public class TestParticipantManager extends ZkTestBase {
       participants[i].syncStart();
     }
 
-    boolean result = ClusterStateVerifier
-        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
-    Assert.assertTrue(result);
+    BestPossibleExternalViewVerifier verifier =
+        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
+            .setZkAddr(ZK_ADDR).build();
+    Assert.assertTrue(verifier.verifyByPolling());
     String oldSessionId = participants[0].getSessionId();
 
     // expire zk-connection on localhost_12918
@@ -239,9 +235,7 @@ public class TestParticipantManager extends ZkTestBase {
     // wait until session expiry callback happens
     TimeUnit.MILLISECONDS.sleep(100);
 
-    result = ClusterStateVerifier
-        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
-    Assert.assertTrue(result);
+    Assert.assertTrue(verifier.verifyByPolling());
     String newSessionId = participants[0].getSessionId();
     Assert.assertNotSame(newSessionId, oldSessionId);
 
@@ -268,7 +262,7 @@ public class TestParticipantManager extends ZkTestBase {
       String instance = message.getTgtName();
       String partition = message.getPartitionName();
       if (instance.equals("localhost_12918") && partition.equals("TestDB0_0")
-          && _done.getAndSet(true) == false) {
+          && !_done.getAndSet(true)) {
         _startCountdown.countDown();
         // this await will be interrupted since we cancel the task during handleNewSession
         _endCountdown.await();
@@ -309,24 +303,24 @@ public class TestParticipantManager extends ZkTestBase {
     // wait transition happens to trigger session expiry
     startCountdown.await();
     String oldSessionId = participants[0].getSessionId();
-    System.out.println("oldSessionId: " + oldSessionId);
     ZkTestHelper.expireSession(participants[0].getZkClient());
 
-    boolean result = ClusterStateVerifier
-        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, clusterName));
-    Assert.assertTrue(result);
+    BestPossibleExternalViewVerifier verifier =
+        new BestPossibleExternalViewVerifier.Builder(clusterName).setZkClient(_gZkClient)
+            .setZkAddr(ZK_ADDR).build();
+    Assert.assertTrue(verifier.verifyByPolling());
 
     String newSessionId = participants[0].getSessionId();
     Assert.assertNotSame(newSessionId, oldSessionId);
 
     // assert interrupt exception error in old session
-    String errPath = PropertyPathBuilder
-        .instanceError(clusterName, "localhost_12918", oldSessionId, "TestDB0", "TestDB0_0");
+    String errPath = PropertyPathBuilder.instanceError(clusterName, "localhost_12918", oldSessionId,
+        "TestDB0", "TestDB0_0");
     ZNRecord error = _gZkClient.readData(errPath);
     Assert.assertNotNull(error,
         "InterruptedException should happen in old session since task is being cancelled during handleNewSession");
     String errString = new String(new ZNRecordSerializer().serialize(error));
-    Assert.assertTrue(errString.indexOf("InterruptedException") != -1);
+    Assert.assertTrue(errString.contains("InterruptedException"));
 
     // cleanup
     controller.syncStop();
diff --git a/helix-core/src/test/java/org/apache/helix/integration/manager/TestZkHelixAdmin.java b/helix-core/src/test/java/org/apache/helix/integration/manager/TestZkHelixAdmin.java
index 0dfdfb4..89c9a48 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/manager/TestZkHelixAdmin.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/manager/TestZkHelixAdmin.java
@@ -37,8 +37,10 @@ import org.apache.helix.model.IdealState;
 import org.apache.helix.task.JobConfig;
 import org.apache.helix.task.JobContext;
 import org.apache.helix.task.TaskPartitionState;
+import org.apache.helix.task.TaskState;
 import org.apache.helix.task.TaskUtil;
 import org.apache.helix.task.Workflow;
+import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
 import org.testng.Assert;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
@@ -83,34 +85,40 @@ public class TestZkHelixAdmin extends TaskTestBase {
   @Test
   public void testEnableDisablePartitions() throws InterruptedException {
     _admin.enablePartition(false, CLUSTER_NAME, (PARTICIPANT_PREFIX + "_" + _startPort),
-        WorkflowGenerator.DEFAULT_TGT_DB, Arrays.asList(new String[] { "TestDB_0", "TestDB_2" }));
+        WorkflowGenerator.DEFAULT_TGT_DB, Arrays.asList("TestDB_0", "TestDB_2"));
     _admin.enablePartition(false, CLUSTER_NAME, (PARTICIPANT_PREFIX + "_" + (_startPort + 1)),
-        WorkflowGenerator.DEFAULT_TGT_DB, Arrays.asList(new String[] { "TestDB_0", "TestDB_2" }));
+        WorkflowGenerator.DEFAULT_TGT_DB, Arrays.asList("TestDB_0", "TestDB_2"));
 
     IdealState idealState =
         _admin.getResourceIdealState(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB);
-    List<String> preferenceList =
-        Arrays.asList(new String[] { "localhost_12919", "localhost_12918" });
+    List<String> preferenceList = Arrays.asList("localhost_12919", "localhost_12918");
     for (String partitionName : idealState.getPartitionSet()) {
       idealState.setPreferenceList(partitionName, preferenceList);
     }
     idealState.setRebalanceMode(IdealState.RebalanceMode.SEMI_AUTO);
     _admin.setResourceIdealState(CLUSTER_NAME, WorkflowGenerator.DEFAULT_TGT_DB, idealState);
 
+    // Let the cluster rebalance
+    BestPossibleExternalViewVerifier verifier =
+        new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient)
+            .setZkAddr(ZK_ADDR).build();
+    Assert.assertTrue(verifier.verifyByPolling());
+
     String workflowName = TestHelper.getTestMethodName();
     Workflow.Builder builder = new Workflow.Builder(workflowName);
-    JobConfig.Builder jobBuilder =
-        new JobConfig.Builder().setWorkflow(workflowName).setCommand(MockTask.TASK_COMMAND)
-            .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
-            .setTargetPartitionStates(Collections.singleton("SLAVE"));
+    JobConfig.Builder jobBuilder = new JobConfig.Builder().setWorkflow(workflowName)
+        .setCommand(MockTask.TASK_COMMAND).setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
+        .setTargetPartitionStates(Collections.singleton("SLAVE"));
     builder.addJob("JOB", jobBuilder);
     _driver.start(builder.build());
-    Thread.sleep(2000L);
+    _driver.pollForJobState(workflowName, TaskUtil.getNamespacedJobName(workflowName, "JOB"),
+        TaskState.IN_PROGRESS);
+    Thread.sleep(3000L);
     JobContext jobContext =
         _driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB"));
-    Assert.assertEquals(jobContext.getPartitionState(0), null);
+    Assert.assertNull(jobContext.getPartitionState(0));
     Assert.assertEquals(jobContext.getPartitionState(1), TaskPartitionState.COMPLETED);
-    Assert.assertEquals(jobContext.getPartitionState(2), null);
+    Assert.assertNull(jobContext.getPartitionState(2));
   }
 
   private List<ViewClusterSourceConfig> generateViewClusterSourceConfig() {
@@ -122,8 +130,8 @@ public class TestZkHelixAdmin extends TaskTestBase {
     List<ViewClusterSourceConfig> sourceConfigs = new ArrayList<>();
     for (int i = 0; i < 3; i++) {
       String clusterName = clusterNamePrefix + i;
-      String configJSON = String
-          .format(testJsonTemplate, clusterName, zkConnection, PropertyType.INSTANCES.name(),
+      String configJSON =
+          String.format(testJsonTemplate, clusterName, zkConnection, PropertyType.INSTANCES.name(),
               PropertyType.EXTERNALVIEW.name(), PropertyType.LIVEINSTANCES.name());
 
       sourceConfigs.add(ViewClusterSourceConfig.fromJson(configJSON));
diff --git a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestCrossClusterMessagingService.java b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestCrossClusterMessagingService.java
index fe38c6d..64dbbea 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestCrossClusterMessagingService.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestCrossClusterMessagingService.java
@@ -64,7 +64,6 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     if (_adminController != null && _adminController.isConnected()) {
       _adminController.syncStop();
     }
-
     deleteCluster(ADMIN_CLUSTER_NAME);
     super.afterClass();
   }
@@ -74,8 +73,8 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     String hostDest = "localhost_" + (START_PORT + 1);
 
     TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory();
-    _participants[1].getMessagingService()
-        .registerMessageHandlerFactory(factory.getMessageTypes(), factory);
+    _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(),
+        factory);
 
     String msgId = new UUID(123, 456).toString();
     Message msg = new Message(factory.getMessageTypes().get(0), msgId);
@@ -93,7 +92,7 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     cr.setClusterName(CLUSTER_NAME);
 
     int nMsgs = _adminController.getMessagingService().send(cr, msg);
-    AssertJUnit.assertTrue(nMsgs == 1);
+    AssertJUnit.assertEquals(nMsgs, 1);
     Thread.sleep(2500);
     AssertJUnit.assertTrue(TestMessagingHandlerFactory._processedMsgIds.contains(para));
 
@@ -106,7 +105,7 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
 
     // nMsgs = _startCMResultMap.get(hostSrc)._manager.getMessagingService().send(cr, msg);
     nMsgs = _adminController.getMessagingService().send(cr, msg);
-    AssertJUnit.assertTrue(nMsgs == 1);
+    AssertJUnit.assertEquals(nMsgs, 1);
     Thread.sleep(2500);
     AssertJUnit.assertTrue(TestMessagingHandlerFactory._processedMsgIds.contains(para));
   }
@@ -116,10 +115,10 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     String hostDest = "localhost_" + (START_PORT + 1);
 
     TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory();
-    _participants[1].getMessagingService()
-        .registerMessageHandlerFactory(factory.getMessageTypes(), factory);
-    _participants[0].getMessagingService()
-        .registerMessageHandlerFactory(factory.getMessageTypes(), factory);
+    _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(),
+        factory);
+    _participants[0].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(),
+        factory);
 
     String msgId = new UUID(123, 456).toString();
     Message msg = new Message(factory.getMessageTypes().get(0), msgId);
@@ -142,7 +141,7 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
 
     Thread.sleep(2000);
     AssertJUnit.assertTrue(TestAsyncCallback._replyedMessageContents.contains("TestReplyMessage"));
-    AssertJUnit.assertTrue(callback.getMessageReplied().size() == 1);
+    AssertJUnit.assertEquals(callback.getMessageReplied().size(), 1);
 
     TestAsyncCallback callback2 = new TestAsyncCallback(500);
     _adminController.getMessagingService().send(cr, msg, callback2, 500);
@@ -163,7 +162,7 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
 
     Thread.sleep(2000);
     AssertJUnit.assertTrue(TestAsyncCallback._replyedMessageContents.contains("TestReplyMessage"));
-    AssertJUnit.assertTrue(callback.getMessageReplied().size() == 1);
+    AssertJUnit.assertEquals(callback.getMessageReplied().size(), 1);
 
     callback2 = new TestAsyncCallback(500);
     _adminController.getMessagingService().send(cr, msg, callback2, 500);
@@ -177,8 +176,8 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     String hostDest = "localhost_" + (START_PORT + 1);
 
     TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory();
-    _participants[1].getMessagingService()
-        .registerMessageHandlerFactory(factory.getMessageTypes(), factory);
+    _participants[1].getMessagingService().registerMessageHandlerFactory(factory.getMessageTypes(),
+        factory);
 
     String msgId = new UUID(123, 456).toString();
     Message msg = new Message(factory.getMessageTypes().get(0), msgId);
@@ -199,10 +198,11 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     int messagesSent =
         _adminController.getMessagingService().sendAndWait(cr, msg, asyncCallback, 60000);
 
-    AssertJUnit.assertTrue(asyncCallback.getMessageReplied().get(0).getRecord()
-        .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage")
-        .equals("TestReplyMessage"));
-    AssertJUnit.assertTrue(asyncCallback.getMessageReplied().size() == 1);
+    AssertJUnit.assertEquals(
+        asyncCallback.getMessageReplied().get(0).getRecord()
+            .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage"),
+        "TestReplyMessage");
+    AssertJUnit.assertEquals(asyncCallback.getMessageReplied().size(), 1);
 
     AsyncCallback asyncCallback2 = new MockAsyncCallback();
     messagesSent = _adminController.getMessagingService().sendAndWait(cr, msg, asyncCallback2, 500);
@@ -210,7 +210,7 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
   }
 
   @Test()
-  public void TestMultiMessageCriteria() throws Exception {
+  public void TestMultiMessageCriteria() {
     for (int i = 0; i < NODE_NR; i++) {
       TestMessagingHandlerFactory factory = new TestMessagingHandlerFactory();
       _participants[i].getMessagingService()
@@ -235,10 +235,11 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     int messageSent1 =
         _adminController.getMessagingService().sendAndWait(cr, msg, callback1, 10000);
 
-    AssertJUnit.assertTrue(callback1.getMessageReplied().get(0).getRecord()
-        .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage")
-        .equals("TestReplyMessage"));
-    AssertJUnit.assertTrue(callback1.getMessageReplied().size() == NODE_NR);
+    AssertJUnit.assertEquals(
+        callback1.getMessageReplied().get(0).getRecord()
+            .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ReplyMessage"),
+        "TestReplyMessage");
+    AssertJUnit.assertEquals(NODE_NR, callback1.getMessageReplied().size());
 
     AsyncCallback callback2 = new MockAsyncCallback();
     int messageSent2 = _adminController.getMessagingService().sendAndWait(cr, msg, callback2, 500);
@@ -249,25 +250,25 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     AsyncCallback callback3 = new MockAsyncCallback();
     int messageSent3 =
         _adminController.getMessagingService().sendAndWait(cr, msg, callback3, 10000);
-    AssertJUnit.assertTrue(callback3.getMessageReplied().size() == _replica);
+    AssertJUnit.assertEquals(_replica, callback3.getMessageReplied().size());
 
     cr.setPartition("TestDB_15");
     AsyncCallback callback4 = new MockAsyncCallback();
     int messageSent4 =
         _adminController.getMessagingService().sendAndWait(cr, msg, callback4, 10000);
-    AssertJUnit.assertTrue(callback4.getMessageReplied().size() == _replica);
+    AssertJUnit.assertEquals(_replica, callback4.getMessageReplied().size());
 
     cr.setPartitionState("SLAVE");
     AsyncCallback callback5 = new MockAsyncCallback();
     int messageSent5 =
         _adminController.getMessagingService().sendAndWait(cr, msg, callback5, 10000);
-    AssertJUnit.assertTrue(callback5.getMessageReplied().size() == _replica - 1);
+    AssertJUnit.assertEquals(_replica - 1, callback5.getMessageReplied().size());
 
     cr.setDataSource(DataSource.IDEALSTATES);
     AsyncCallback callback6 = new MockAsyncCallback();
     int messageSent6 =
         _adminController.getMessagingService().sendAndWait(cr, msg, callback6, 10000);
-    AssertJUnit.assertTrue(callback6.getMessageReplied().size() == _replica - 1);
+    AssertJUnit.assertEquals(_replica - 1, callback6.getMessageReplied().size());
   }
 
   @Test()
@@ -299,8 +300,8 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
 
     AssertJUnit.assertTrue(callback1.getMessageReplied().get(0).getRecord()
         .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult")
-        .indexOf(_hostSrc) != -1);
-    AssertJUnit.assertTrue(callback1.getMessageReplied().size() == 1);
+        .contains(_hostSrc));
+    AssertJUnit.assertEquals(callback1.getMessageReplied().size(), 1);
 
     msgId = UUID.randomUUID().toString();
     msg.setMsgId(msgId);
@@ -310,9 +311,9 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
 
     AssertJUnit.assertTrue(callback2.getMessageReplied().get(0).getRecord()
         .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult")
-        .indexOf(_hostSrc) != -1);
+        .contains(_hostSrc));
 
-    AssertJUnit.assertTrue(callback2.getMessageReplied().size() == 1);
+    AssertJUnit.assertEquals(callback2.getMessageReplied().size(), 1);
 
     msgId = UUID.randomUUID().toString();
     msg.setMsgId(msgId);
@@ -321,9 +322,9 @@ public class TestCrossClusterMessagingService extends TestMessagingService {
     messagesSent = _adminController.getMessagingService().sendAndWait(cr, msg, callback3, 10000);
     AssertJUnit.assertTrue(callback3.getMessageReplied().get(0).getRecord()
         .getMapField(Message.Attributes.MESSAGE_RESULT.toString()).get("ControllerResult")
-        .indexOf(_hostSrc) != -1);
+        .contains(_hostSrc));
 
-    AssertJUnit.assertTrue(callback3.getMessageReplied().size() == 1);
+    AssertJUnit.assertEquals(callback3.getMessageReplied().size(), 1);
   }
 
   @Test(enabled = false)
diff --git a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestGroupCommitAddBackData.java b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestGroupCommitAddBackData.java
index 70d4425..6e7bfc7 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestGroupCommitAddBackData.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestGroupCommitAddBackData.java
@@ -1,22 +1,34 @@
 package org.apache.helix.integration.messaging;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.Date;
-import java.util.Random;
 import java.util.UUID;
 import org.apache.helix.HelixDataAccessor;
 import org.apache.helix.HelixManager;
 import org.apache.helix.HelixManagerFactory;
 import org.apache.helix.InstanceType;
-import org.apache.helix.PropertyKey;
 import org.apache.helix.common.ZkTestBase;
-import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
-import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.integration.manager.MockParticipantManager;
 import org.apache.helix.integration.task.WorkflowGenerator;
 import org.apache.helix.model.Message;
-import org.apache.helix.tools.ClusterStateVerifier;
-import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
-import org.apache.helix.tools.ClusterVerifiers.HelixClusterVerifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
@@ -35,8 +47,6 @@ public class TestGroupCommitAddBackData extends ZkTestBase {
 
   private MockParticipantManager _participant;
 
-  private int _replica = 3;
-
   @BeforeClass
   public void beforeClass() throws Exception {
     // Logger.getRootLogger().setLevel(Level.INFO);
@@ -50,8 +60,8 @@ public class TestGroupCommitAddBackData extends ZkTestBase {
     _participant.syncStart();
 
     // create cluster manager
-    _manager = HelixManagerFactory
-        .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
+    _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin",
+        InstanceType.ADMINISTRATOR, ZK_ADDR);
     _manager.connect();
   }
 
@@ -72,6 +82,7 @@ public class TestGroupCommitAddBackData extends ZkTestBase {
       } catch (Exception ex) {
         System.err.println(
             "Failed to delete cluster " + CLUSTER_NAME + ", error: " + ex.getLocalizedMessage());
+        _gSetupTool.deleteCluster(CLUSTER_NAME);
       }
     }
 
@@ -99,9 +110,9 @@ public class TestGroupCommitAddBackData extends ZkTestBase {
           accessor.keyBuilder().message(_participant.getInstanceName(), dropped.getMsgId()),
           dropped);
       Assert.assertTrue(waitForMessageProcessed(accessor, dropped.getMsgId()));
-      Assert.assertFalse(accessor.getBaseDataAccessor().exists(accessor.keyBuilder()
-          .currentState(_participant.getInstanceName(), _participant.getSessionId(),
-              WorkflowGenerator.DEFAULT_TGT_DB).getPath(), 0));
+      Assert.assertFalse(accessor.getBaseDataAccessor()
+          .exists(accessor.keyBuilder().currentState(_participant.getInstanceName(),
+              _participant.getSessionId(), WorkflowGenerator.DEFAULT_TGT_DB).getPath(), 0));
     }
   }
 
diff --git a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestMessageThrottle2.java b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestMessageThrottle2.java
index 4ae41ac..b6971e0 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestMessageThrottle2.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestMessageThrottle2.java
@@ -24,8 +24,10 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Date;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import org.apache.helix.ControllerChangeListener;
 import org.apache.helix.ExternalViewChangeListener;
 import org.apache.helix.HelixAdmin;
@@ -65,106 +67,107 @@ import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.Test;
 
-// test case from Ming Fang
 public class TestMessageThrottle2 extends ZkTestBase {
-  final static String clusterName = "TestMessageThrottle2";
-  final static String resourceName = "MyResource";
+  private final static String _clusterName = "TestMessageThrottle2";
+  private final static String _resourceName = "MyResource";
+  private HelixManager _helixController;
 
   @Test
   public void test() throws Exception {
-    System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis()));
+    System.out.println("START " + _clusterName + " at " + new Date(System.currentTimeMillis()));
+
+    // Keep mock participant references so that they could be shut down after testing
+    Set<MyProcess> participants = new HashSet<>();
 
     startAdmin();
     startController();
 
     // start node2 first
-    Node.main(new String[] {
-      "2"
-    });
+    participants.add(Node.main(new String[] {
+        "2"
+    }));
 
     // wait for node2 becoming MASTER
-    final Builder keyBuilder = new Builder(clusterName);
+    final Builder keyBuilder = new Builder(_clusterName);
     final HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
-    TestHelper.verify(new TestHelper.Verifier() {
-
-      @Override
-      public boolean verify() throws Exception {
-        ExternalView view = accessor.getProperty(keyBuilder.externalView(resourceName));
-        String state = null;
-
-        if (view != null) {
-          Map<String, String> map = view.getStateMap(resourceName);
-          if (map != null) {
-            state = map.get("node2");
-          }
+        new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<>(_gZkClient));
+    TestHelper.verify(() -> {
+      ExternalView view = accessor.getProperty(keyBuilder.externalView(_resourceName));
+      String state = null;
+
+      if (view != null) {
+        Map<String, String> map = view.getStateMap(_resourceName);
+        if (map != null) {
+          state = map.get("node2");
         }
-        return state != null && state.equals("MASTER");
       }
+      return state != null && state.equals("MASTER");
     }, 10 * 1000);
 
     // start node 1
-    Node.main(new String[] {
-      "1"
-    });
+    participants.add(Node.main(new String[] {
+        "1"
+    }));
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR,
-            clusterName));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName));
     Assert.assertTrue(result);
 
-    System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis()));
+    // Clean up after testing
+    _helixController.disconnect();
+    participants.forEach(MyProcess::stop);
+    deleteCluster(_clusterName);
+    System.out.println("END " + _clusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
-  void startController() throws Exception {
-    // start helixController
+  private void startController() throws Exception {
+    // start _helixController
     System.out.println(String.format("Starting Controller{Cluster:%s, Port:%s, Zookeeper:%s}",
-        clusterName, 12000, ZK_ADDR));
-    HelixManager helixController =
-        HelixControllerMain.startHelixController(ZK_ADDR, clusterName, "localhost_" + 12000,
-            HelixControllerMain.STANDALONE);
+        _clusterName, 12000, ZK_ADDR));
+    _helixController = HelixControllerMain.startHelixController(ZK_ADDR, _clusterName,
+        "localhost_" + 12000, HelixControllerMain.STANDALONE);
 
-    StatusPrinter statusPrinter = new StatusPrinter();
-    statusPrinter.registerWith(helixController);
+    // StatusPrinter statusPrinter = new StatusPrinter();
+    // statusPrinter.registerWith(_helixController);
   }
 
-  void startAdmin() throws Exception {
+  private void startAdmin() {
     HelixAdmin admin = new ZKHelixAdmin(ZK_ADDR);
 
     // create cluster
-    System.out.println("Creating cluster: " + clusterName);
-    admin.addCluster(clusterName, true);
+    System.out.println("Creating cluster: " + _clusterName);
+    admin.addCluster(_clusterName, true);
 
     // add MasterSlave state mode definition
-    admin.addStateModelDef(clusterName, "MasterSlave", new StateModelDefinition(
-        generateConfigForMasterSlave()));
+    admin.addStateModelDef(_clusterName, "MasterSlave",
+        new StateModelDefinition(generateConfigForMasterSlave()));
 
     // ideal-state znrecord
-    ZNRecord record = new ZNRecord(resourceName);
+    ZNRecord record = new ZNRecord(_resourceName);
     record.setSimpleField("IDEAL_STATE_MODE", "AUTO");
     record.setSimpleField("NUM_PARTITIONS", "1");
     record.setSimpleField("REPLICAS", "2");
     record.setSimpleField("STATE_MODEL_DEF_REF", "MasterSlave");
-    record.setListField(resourceName, Arrays.asList("node1", "node2"));
+    record.setListField(_resourceName, Arrays.asList("node1", "node2"));
 
-    admin.setResourceIdealState(clusterName, resourceName, new IdealState(record));
+    admin.setResourceIdealState(_clusterName, _resourceName, new IdealState(record));
 
     ConstraintItemBuilder builder = new ConstraintItemBuilder();
 
     // limit one transition message at a time across the entire cluster
     builder.addConstraintAttribute("MESSAGE_TYPE", "STATE_TRANSITION")
-    // .addConstraintAttribute("INSTANCE", ".*") // un-comment this line if using instance-level
-    // constraint
+        // .addConstraintAttribute("INSTANCE", ".*") // un-comment this line if using instance-level
+        // constraint
         .addConstraintAttribute("CONSTRAINT_VALUE", "1");
-    admin.setConstraint(clusterName, ClusterConstraints.ConstraintType.MESSAGE_CONSTRAINT,
+    admin.setConstraint(_clusterName, ClusterConstraints.ConstraintType.MESSAGE_CONSTRAINT,
         "constraint1", builder.build());
   }
 
-  ZNRecord generateConfigForMasterSlave() {
+  private ZNRecord generateConfigForMasterSlave() {
     ZNRecord record = new ZNRecord("MasterSlave");
     record.setSimpleField(
         StateModelDefinition.StateModelDefinitionProperty.INITIAL_STATE.toString(), "OFFLINE");
-    List<String> statePriorityList = new ArrayList<String>();
+    List<String> statePriorityList = new ArrayList<>();
     statePriorityList.add("MASTER");
     statePriorityList.add("SLAVE");
     statePriorityList.add("OFFLINE");
@@ -175,53 +178,62 @@ public class TestMessageThrottle2 extends ZkTestBase {
         statePriorityList);
     for (String state : statePriorityList) {
       String key = state + ".meta";
-      Map<String, String> metadata = new HashMap<String, String>();
-      if (state.equals("MASTER")) {
+      Map<String, String> metadata = new HashMap<>();
+      switch (state) {
+      case "MASTER":
         metadata.put("count", "1");
         record.setMapField(key, metadata);
-      } else if (state.equals("SLAVE")) {
+        break;
+      case "SLAVE":
         metadata.put("count", "R");
         record.setMapField(key, metadata);
-      } else if (state.equals("OFFLINE")) {
-        metadata.put("count", "-1");
-        record.setMapField(key, metadata);
-      } else if (state.equals("DROPPED")) {
-        metadata.put("count", "-1");
-        record.setMapField(key, metadata);
-      } else if (state.equals("ERROR")) {
+        break;
+      case "OFFLINE":
+      case "DROPPED":
+      case "ERROR":
         metadata.put("count", "-1");
         record.setMapField(key, metadata);
+        break;
       }
     }
     for (String state : statePriorityList) {
       String key = state + ".next";
-      if (state.equals("MASTER")) {
-        Map<String, String> metadata = new HashMap<String, String>();
+      switch (state) {
+      case "MASTER": {
+        Map<String, String> metadata = new HashMap<>();
         metadata.put("SLAVE", "SLAVE");
         metadata.put("OFFLINE", "SLAVE");
         metadata.put("DROPPED", "SLAVE");
         record.setMapField(key, metadata);
-      } else if (state.equals("SLAVE")) {
-        Map<String, String> metadata = new HashMap<String, String>();
+        break;
+      }
+      case "SLAVE": {
+        Map<String, String> metadata = new HashMap<>();
         metadata.put("MASTER", "MASTER");
         metadata.put("OFFLINE", "OFFLINE");
         metadata.put("DROPPED", "OFFLINE");
         record.setMapField(key, metadata);
-      } else if (state.equals("OFFLINE")) {
-        Map<String, String> metadata = new HashMap<String, String>();
+        break;
+      }
+      case "OFFLINE": {
+        Map<String, String> metadata = new HashMap<>();
         metadata.put("SLAVE", "SLAVE");
         metadata.put("MASTER", "SLAVE");
         metadata.put("DROPPED", "DROPPED");
         record.setMapField(key, metadata);
-      } else if (state.equals("ERROR")) {
-        Map<String, String> metadata = new HashMap<String, String>();
+        break;
+      }
+      case "ERROR": {
+        Map<String, String> metadata = new HashMap<>();
         metadata.put("OFFLINE", "OFFLINE");
         record.setMapField(key, metadata);
+        break;
+      }
       }
     }
 
     // change the transition priority list
-    List<String> stateTransitionPriorityList = new ArrayList<String>();
+    List<String> stateTransitionPriorityList = new ArrayList<>();
     stateTransitionPriorityList.add("SLAVE-MASTER");
     stateTransitionPriorityList.add("OFFLINE-SLAVE");
     stateTransitionPriorityList.add("MASTER-SLAVE");
@@ -231,38 +243,36 @@ public class TestMessageThrottle2 extends ZkTestBase {
         StateModelDefinition.StateModelDefinitionProperty.STATE_TRANSITION_PRIORITYLIST.toString(),
         stateTransitionPriorityList);
     return record;
-    // ZNRecordSerializer serializer = new ZNRecordSerializer();
-    // System.out.println(new String(serializer.serialize(record)));
   }
 
   static final class MyProcess {
-    private final String instanceName;
-    private HelixManager helixManager;
+    private final String _instanceName;
+    private HelixManager _helixManager;
 
     public MyProcess(String instanceName) {
-      this.instanceName = instanceName;
+      this._instanceName = instanceName;
     }
 
     public void start() throws Exception {
-      helixManager =
-          new ZKHelixManager(clusterName, instanceName, InstanceType.PARTICIPANT, ZK_ADDR);
+      _helixManager =
+          new ZKHelixManager(_clusterName, _instanceName, InstanceType.PARTICIPANT, ZK_ADDR);
       {
         // hack to set sessionTimeout
         Field sessionTimeout = ZKHelixManager.class.getDeclaredField("_sessionTimeout");
         sessionTimeout.setAccessible(true);
-        sessionTimeout.setInt(helixManager, 1000);
+        sessionTimeout.setInt(_helixManager, 1000);
       }
 
-      StateMachineEngine stateMach = helixManager.getStateMachineEngine();
-      stateMach.registerStateModelFactory("MasterSlave", new MyStateModelFactory(helixManager));
-      helixManager.connect();
+      StateMachineEngine stateMach = _helixManager.getStateMachineEngine();
+      stateMach.registerStateModelFactory("MasterSlave", new MyStateModelFactory(_helixManager));
+      _helixManager.connect();
 
-      StatusPrinter statusPrinter = new StatusPrinter();
-      statusPrinter.registerWith(helixManager);
+      // StatusPrinter statusPrinter = new StatusPrinter();
+      // statusPrinter.registerWith(_helixManager);
     }
 
     public void stop() {
-      helixManager.disconnect();
+      _helixManager.disconnect();
     }
   }
 
@@ -343,7 +353,7 @@ public class TestMessageThrottle2 extends ZkTestBase {
 
     // --------------------------- main() method ---------------------------
 
-    public static void main(String[] args) throws Exception {
+    public static MyProcess main(String[] args) throws Exception {
       if (args.length < 1) {
         LOGGER.info("usage: id");
         System.exit(0);
@@ -352,7 +362,8 @@ public class TestMessageThrottle2 extends ZkTestBase {
       String instanceName = "node" + id;
 
       addInstanceConfig(instanceName);
-      startProcess(instanceName);
+      // Return the thread so that it could be interrupted after testing
+      return startProcess(instanceName);
     }
 
     private static void addInstanceConfig(String instanceName) {
@@ -361,15 +372,15 @@ public class TestMessageThrottle2 extends ZkTestBase {
 
       InstanceConfig instanceConfig = null;
       try {
-        instanceConfig = admin.getInstanceConfig(clusterName, instanceName);
-      } catch (Exception e) {
+        instanceConfig = admin.getInstanceConfig(_clusterName, instanceName);
+      } catch (Exception ignored) {
       }
       if (instanceConfig == null) {
         InstanceConfig config = new InstanceConfig(instanceName);
         config.setHostName("localhost");
         config.setInstanceEnabled(true);
         echo("Adding InstanceConfig:" + config);
-        admin.addInstance(clusterName, config);
+        admin.addInstance(_clusterName, config);
       }
     }
 
@@ -377,9 +388,10 @@ public class TestMessageThrottle2 extends ZkTestBase {
       LOGGER.info(obj.toString());
     }
 
-    private static void startProcess(String instanceName) throws Exception {
+    private static MyProcess startProcess(String instanceName) throws Exception {
       MyProcess process = new MyProcess(instanceName);
       process.start();
+      return process;
     }
   }
 
@@ -387,8 +399,6 @@ public class TestMessageThrottle2 extends ZkTestBase {
       ExternalViewChangeListener, LiveInstanceChangeListener, ControllerChangeListener {
     // ------------------------------ FIELDS ------------------------------
 
-    private HelixManager helixManager;
-
     // ------------------------ INTERFACE METHODS ------------------------
 
     // --------------------- Interface ControllerChangeListener
@@ -428,8 +438,8 @@ public class TestMessageThrottle2 extends ZkTestBase {
     public void onInstanceConfigChange(List<InstanceConfig> instanceConfigs,
         NotificationContext context) {
       for (InstanceConfig instanceConfig : instanceConfigs) {
-        System.out.println("StatusPrinter.onInstanceConfigChange:" + "instanceConfig = "
-            + instanceConfig);
+        System.out.println(
+            "StatusPrinter.onInstanceConfigChange:" + "instanceConfig = " + instanceConfig);
       }
     }
 
@@ -447,8 +457,7 @@ public class TestMessageThrottle2 extends ZkTestBase {
 
     // -------------------------- OTHER METHODS --------------------------
 
-    public void registerWith(HelixManager helixManager) throws Exception {
-      this.helixManager = helixManager;
+    void registerWith(HelixManager helixManager) throws Exception {
       helixManager.addIdealStateChangeListener(this);
       helixManager.addInstanceConfigChangeListener(this);
       helixManager.addExternalViewChangeListener(this);
diff --git a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PMessageSemiAuto.java b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PMessageSemiAuto.java
index 9dad564..cbe3504 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PMessageSemiAuto.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PMessageSemiAuto.java
@@ -64,10 +64,10 @@ public class TestP2PMessageSemiAuto extends ZkTestBase {
   HelixDataAccessor _accessor;
 
   @BeforeClass
-  public void beforeClass()
-      throws InterruptedException {
-    System.out.println(
-        "START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
+  public void beforeClass() throws Exception {
+    super.beforeClass();
+    System.out
+        .println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
 
     // setup storage cluster
     _gSetupTool.addCluster(CLUSTER_NAME, true);
@@ -97,7 +97,8 @@ public class TestP2PMessageSemiAuto extends ZkTestBase {
     _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
     _controller.syncStart();
 
-    _clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient).build();
+    _clusterVerifier =
+        new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient).build();
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     _configAccessor = new ConfigAccessor(_gZkClient);
@@ -108,9 +109,7 @@ public class TestP2PMessageSemiAuto extends ZkTestBase {
   public void afterClass() throws Exception {
     _controller.syncStop();
     for (MockParticipantManager p : _participants) {
-      if (p.isConnected()) {
-        p.syncStop();
-      }
+      p.syncStop();
     }
     deleteCluster(CLUSTER_NAME);
     System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
@@ -123,11 +122,12 @@ public class TestP2PMessageSemiAuto extends ZkTestBase {
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, false);
 
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
-    verifyP2PMessage(DB_NAME_1,_instances.get(1), MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1);
-    verifyP2PMessage(DB_NAME_2,_instances.get(1), MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1);
-
+    verifyP2PMessage(DB_NAME_1, _instances.get(1), MasterSlaveSMD.States.MASTER.name(),
+        _controller.getInstanceName(), 1);
+    verifyP2PMessage(DB_NAME_2, _instances.get(1), MasterSlaveSMD.States.MASTER.name(),
+        _controller.getInstanceName(), 1);
 
-    //re-enable the old master
+    // re-enable the old master
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, true);
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
@@ -137,67 +137,78 @@ public class TestP2PMessageSemiAuto extends ZkTestBase {
         _controller.getInstanceName(), 1);
   }
 
-  @Test (dependsOnMethods = {"testP2PStateTransitionDisabled"})
+  @Test(dependsOnMethods = {
+      "testP2PStateTransitionDisabled"
+  })
   public void testP2PStateTransitionEnabledInCluster() {
     enableP2PInCluster(CLUSTER_NAME, _configAccessor, true);
-    enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_1,false);
-    enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_2,false);
+    enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_1, false);
+    enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_2, false);
 
     // disable the master instance
     String prevMasterInstance = _instances.get(0);
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, false);
 
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
-    verifyP2PMessage(DB_NAME_1, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), prevMasterInstance);
-    verifyP2PMessage(DB_NAME_2, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), prevMasterInstance);
+    verifyP2PMessage(DB_NAME_1, _instances.get(1), MasterSlaveSMD.States.MASTER.name(),
+        prevMasterInstance);
+    verifyP2PMessage(DB_NAME_2, _instances.get(1), MasterSlaveSMD.States.MASTER.name(),
+        prevMasterInstance);
 
-    //re-enable the old master
+    // re-enable the old master
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, true);
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
-    verifyP2PMessage(DB_NAME_1, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _instances.get(
-        1));
-    verifyP2PMessage(DB_NAME_2, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _instances.get(
-        1));
+    verifyP2PMessage(DB_NAME_1, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(),
+        _instances.get(1));
+    verifyP2PMessage(DB_NAME_2, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(),
+        _instances.get(1));
   }
 
-  @Test (dependsOnMethods = {"testP2PStateTransitionDisabled"})
+  @Test(dependsOnMethods = {
+      "testP2PStateTransitionDisabled"
+  })
   public void testP2PStateTransitionEnabledInResource() {
     enableP2PInCluster(CLUSTER_NAME, _configAccessor, false);
-    enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_1,true);
-    enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_2,false);
-
+    enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_1, true);
+    enableP2PInResource(CLUSTER_NAME, _configAccessor, DB_NAME_2, false);
 
     // disable the master instance
     String prevMasterInstance = _instances.get(0);
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, false);
 
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
-    verifyP2PMessage(DB_NAME_1, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), prevMasterInstance);
-    verifyP2PMessage(DB_NAME_2, _instances.get(1), MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1);
-
+    verifyP2PMessage(DB_NAME_1, _instances.get(1), MasterSlaveSMD.States.MASTER.name(),
+        prevMasterInstance);
+    verifyP2PMessage(DB_NAME_2, _instances.get(1), MasterSlaveSMD.States.MASTER.name(),
+        _controller.getInstanceName(), 1);
 
-    //re-enable the old master
+    // re-enable the old master
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, prevMasterInstance, true);
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
-    verifyP2PMessage(DB_NAME_1, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _instances.get(1));
-    verifyP2PMessage(DB_NAME_2, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(), _controller.getInstanceName(), 1);
+    verifyP2PMessage(DB_NAME_1, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(),
+        _instances.get(1));
+    verifyP2PMessage(DB_NAME_2, prevMasterInstance, MasterSlaveSMD.States.MASTER.name(),
+        _controller.getInstanceName(), 1);
   }
 
-  private void verifyP2PMessage(String dbName, String instance, String expectedState, String expectedTriggerHost) {
-    verifyP2PMessage(dbName, instance, expectedState, expectedTriggerHost, 0.6);
+  private void verifyP2PMessage(String dbName, String instance, String expectedState,
+      String expectedTriggerHost) {
+    // Use 0.1 as the expected ratio. Here we want to check the presence of P2P messages
+    verifyP2PMessage(dbName, instance, expectedState, expectedTriggerHost, 0.1);
   }
 
-  private void verifyP2PMessage(String dbName, String instance, String expectedState, String expectedTriggerHost, double expectedRatio) {
+  private void verifyP2PMessage(String dbName, String instance, String expectedState,
+      String expectedTriggerHost, double expectedRatio) {
     ResourceControllerDataProvider dataCache = new ResourceControllerDataProvider(CLUSTER_NAME);
     dataCache.refresh(_accessor);
 
     Map<String, LiveInstance> liveInstanceMap = dataCache.getLiveInstances();
     LiveInstance liveInstance = liveInstanceMap.get(instance);
 
-    Map<String, CurrentState> currentStateMap = dataCache.getCurrentState(instance,
-        liveInstance.getSessionId());
+    Map<String, CurrentState> currentStateMap =
+        dataCache.getCurrentState(instance, liveInstance.getSessionId());
     Assert.assertNotNull(currentStateMap);
     CurrentState currentState = currentStateMap.get(dbName);
     Assert.assertNotNull(currentState);
@@ -211,15 +222,15 @@ public class TestP2PMessageSemiAuto extends ZkTestBase {
           dbName + " Partition " + partition + "'s state is different as expected!");
       String triggerHost = currentState.getTriggerHost(partition);
       if (triggerHost.equals(expectedTriggerHost)) {
-        expectedHost ++;
+        expectedHost++;
       }
-      total ++;
+      total++;
     }
 
     double ratio = ((double) expectedHost) / ((double) total);
-    Assert.assertTrue(ratio >= expectedRatio, String
-        .format("Only %d out of %d percent transitions to Master were triggered by expected host!",
+    Assert.assertTrue(ratio >= expectedRatio,
+        String.format(
+            "Only %d out of %d percent transitions to Master were triggered by expected host!",
             expectedHost, total));
   }
 }
-
diff --git a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PNoDuplicatedMessage.java b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PNoDuplicatedMessage.java
index aead515..7f0f361 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PNoDuplicatedMessage.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PNoDuplicatedMessage.java
@@ -126,9 +126,7 @@ public class TestP2PNoDuplicatedMessage extends ZkTestBase {
   public void afterClass() throws Exception {
     _controller.syncStop();
     for (MockParticipantManager p : _participants) {
-      if (p.isConnected()) {
-        p.syncStop();
-      }
+      p.syncStop();
     }
     deleteCluster(CLUSTER_NAME);
     System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
diff --git a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PSingleTopState.java b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PSingleTopState.java
index a1b37b2..e954cfe 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PSingleTopState.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestP2PSingleTopState.java
@@ -41,15 +41,12 @@ import org.apache.helix.model.MasterSlaveSMD;
 import org.apache.helix.model.Message;
 import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
 import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 public class TestP2PSingleTopState extends ZkTestBase {
-  private static Logger logger = LoggerFactory.getLogger(TestP2PSingleTopState.class);
 
   final String CLASS_NAME = getShortClassName();
   final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
@@ -100,7 +97,7 @@ public class TestP2PSingleTopState extends ZkTestBase {
     _accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
 
     enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, true, 1000000);
-    //enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, false);
+    // enableDelayRebalanceInCluster(_gZkClient, CLUSTER_NAME, false);
     enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
     enableP2PInCluster(CLUSTER_NAME, _configAccessor, true);
 
@@ -123,9 +120,7 @@ public class TestP2PSingleTopState extends ZkTestBase {
   public void afterClass() throws Exception {
     _controller.syncStop();
     for (MockParticipantManager p : _participants) {
-      if (p.isConnected()) {
-        p.syncStop();
-      }
+      p.syncStop();
     }
     deleteCluster(CLUSTER_NAME);
     System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
@@ -137,11 +132,11 @@ public class TestP2PSingleTopState extends ZkTestBase {
     for (String ins : _instances) {
       System.out.println("Disable " + ins);
       _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, ins, false);
-      Thread.sleep (1000);
+      Thread.sleep(1000L);
       Assert.assertTrue(_clusterVerifier.verifyByPolling());
       System.out.println("Enable " + ins);
       _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, ins, true);
-      Thread.sleep(1000);
+      Thread.sleep(1000L);
       Assert.assertTrue(_clusterVerifier.verifyByPolling());
     }
 
@@ -178,7 +173,7 @@ public class TestP2PSingleTopState extends ZkTestBase {
 
     String _instanceName;
 
-    public TestTransition(String instanceName) {
+    TestTransition(String instanceName) {
       _instanceName = instanceName;
     }
 
@@ -202,7 +197,7 @@ public class TestP2PSingleTopState extends ZkTestBase {
         }
       }
 
-      ExternalViews.putIfAbsent(key, new ConcurrentHashMap<String, String>());
+      ExternalViews.putIfAbsent(key, new ConcurrentHashMap<>());
       if (to.equalsIgnoreCase("DROPPED")) {
         ExternalViews.get(key).remove(_instanceName);
       } else {
@@ -211,4 +206,3 @@ public class TestP2PSingleTopState extends ZkTestBase {
     }
   }
 }
-
diff --git a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestSchedulerMessage.java b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestSchedulerMessage.java
index 7ded666..173a80a 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/messaging/TestSchedulerMessage.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/messaging/TestSchedulerMessage.java
@@ -62,7 +62,7 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
   public static class MockAsyncCallback extends AsyncCallback {
     Message _message;
 
-    public MockAsyncCallback() {
+    MockAsyncCallback() {
     }
 
     @Override
@@ -77,10 +77,10 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     }
   }
 
-  TestMessagingHandlerFactory _factory = new TestMessagingHandlerFactory();
+  private TestMessagingHandlerFactory _factory = new TestMessagingHandlerFactory();
 
   public static class TestMessagingHandlerFactory implements MultiTypeMessageHandlerFactory {
-    public Map<String, Set<String>> _results = new ConcurrentHashMap<String, Set<String>>();
+    final Map<String, Set<String>> _results = new ConcurrentHashMap<>();
 
     @Override
     public MessageHandler createHandler(Message message, NotificationContext context) {
@@ -92,7 +92,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       return "TestParticipant";
     }
 
-    @Override public List<String> getMessageTypes() {
+    @Override
+    public List<String> getMessageTypes() {
       return ImmutableList.of("TestParticipant");
     }
 
@@ -103,24 +104,22 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     }
 
     public class TestMessagingHandler extends MessageHandler {
-      public TestMessagingHandler(Message message, NotificationContext context) {
+      TestMessagingHandler(Message message, NotificationContext context) {
         super(message, context);
         // TODO Auto-generated constructor stub
       }
 
       @Override
-      public HelixTaskResult handleMessage() throws InterruptedException {
+      public HelixTaskResult handleMessage() {
         HelixTaskResult result = new HelixTaskResult();
         result.setSuccess(true);
-        String destName = _message.getTgtName();
         result.getTaskResultMap().put("Message", _message.getMsgId());
         synchronized (_results) {
           if (!_results.containsKey(_message.getPartitionName())) {
-            _results.put(_message.getPartitionName(), new ConcurrentSkipListSet<String>());
+            _results.put(_message.getPartitionName(), new ConcurrentSkipListSet<>());
           }
         }
         _results.get(_message.getPartitionName()).add(_message.getMsgId());
-        // System.err.println("Message " + _message.getMsgId() + " executed");
         return result;
       }
 
@@ -132,9 +131,9 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
   }
 
   public static class TestMessagingHandlerFactoryLatch implements MultiTypeMessageHandlerFactory {
-    public volatile CountDownLatch _latch = new CountDownLatch(1);
-    public int _messageCount = 0;
-    public Map<String, Set<String>> _results = new ConcurrentHashMap<String, Set<String>>();
+    volatile CountDownLatch _latch = new CountDownLatch(1);
+    int _messageCount = 0;
+    final Map<String, Set<String>> _results = new ConcurrentHashMap<>();
 
     @Override
     public synchronized MessageHandler createHandler(Message message, NotificationContext context) {
@@ -142,7 +141,7 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       return new TestMessagingHandlerLatch(message, context);
     }
 
-    public synchronized void signal() {
+    synchronized void signal() {
       _latch.countDown();
       _latch = new CountDownLatch(1);
     }
@@ -152,7 +151,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       return "TestMessagingHandlerLatch";
     }
 
-    @Override public List<String> getMessageTypes() {
+    @Override
+    public List<String> getMessageTypes() {
       return ImmutableList.of("TestMessagingHandlerLatch");
     }
 
@@ -162,7 +162,7 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     }
 
     public class TestMessagingHandlerLatch extends MessageHandler {
-      public TestMessagingHandlerLatch(Message message, NotificationContext context) {
+      TestMessagingHandlerLatch(Message message, NotificationContext context) {
         super(message, context);
         // TODO Auto-generated constructor stub
       }
@@ -176,11 +176,10 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
         String destName = _message.getTgtName();
         synchronized (_results) {
           if (!_results.containsKey(_message.getPartitionName())) {
-            _results.put(_message.getPartitionName(), new ConcurrentSkipListSet<String>());
+            _results.put(_message.getPartitionName(), new ConcurrentSkipListSet<>());
           }
         }
         _results.get(_message.getPartitionName()).add(destName);
-        // System.err.println("Message " + _message.getMsgId() + " executed");
         return result;
       }
 
@@ -196,10 +195,10 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     _factory._results.clear();
     HelixManager manager = null;
     for (int i = 0; i < NODE_NR; i++) {
-      _participants[i].getMessagingService().registerMessageHandlerFactory(
-          _factory.getMessageTypes(), _factory);
+      _participants[i].getMessagingService()
+          .registerMessageHandlerFactory(_factory.getMessageTypes(), _factory);
 
-      manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager;
+      manager = _participants[i];
     }
 
     Message schedulerMessage =
@@ -208,8 +207,6 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     schedulerMessage.setTgtName("CONTROLLER");
     // TODO: change it to "ADMIN" ?
     schedulerMessage.setSrcName("CONTROLLER");
-    // schedulerMessage.getRecord().setSimpleField(DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE,
-    // "TestSchedulerMsg");
     // Template for the individual message sent to each participant
     Message msg = new Message(_factory.getMessageTypes().get(0), "Template");
     msg.setTgtSessionId("*");
@@ -248,16 +245,15 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     }
 
     Assert.assertEquals(_PARTITIONS, _factory._results.size());
-    PropertyKey controllerTaskStatus =
-        keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(),
-            schedulerMessage.getMsgId());
+    PropertyKey controllerTaskStatus = keyBuilder
+        .controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), schedulerMessage.getMsgId());
 
     int messageResultCount = 0;
     for (int i = 0; i < 10; i++) {
       Thread.sleep(1000);
       ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord();
-      Assert.assertTrue(statusUpdate.getMapField("SentMessageCount").get("MessageCount")
-          .equals("" + (_PARTITIONS * 3)));
+      Assert.assertEquals("" + (_PARTITIONS * 3),
+          statusUpdate.getMapField("SentMessageCount").get("MessageCount"));
       for (String key : statusUpdate.getMapFields().keySet()) {
         if (key.startsWith("MessageResult ")) {
           messageResultCount++;
@@ -278,7 +274,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     Assert.assertEquals(count, _PARTITIONS * 3);
 
     // test the ZkPathDataDumpTask
-    String controllerStatusPath = PropertyPathBuilder.controllerStatusUpdate(manager.getClusterName());
+    String controllerStatusPath =
+        PropertyPathBuilder.controllerStatusUpdate(manager.getClusterName());
     List<String> subPaths = _gZkClient.getChildren(controllerStatusPath);
     Assert.assertTrue(subPaths.size() > 0);
     for (String subPath : subPaths) {
@@ -287,10 +284,10 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       Assert.assertTrue(subsubPaths.size() > 0);
     }
 
-    String instanceStatusPath =
-        PropertyPathBuilder.instanceStatusUpdate(manager.getClusterName(), "localhost_" + (START_PORT));
+    String instanceStatusPath = PropertyPathBuilder.instanceStatusUpdate(manager.getClusterName(),
+        "localhost_" + (START_PORT));
     subPaths = _gZkClient.getChildren(instanceStatusPath);
-    Assert.assertTrue(subPaths.size() == 0);
+    Assert.assertEquals(subPaths.size(), 0);
     for (String subPath : subPaths) {
       String nextPath = instanceStatusPath + "/" + subPath;
       List<String> subsubPaths = _gZkClient.getChildren(nextPath);
@@ -309,18 +306,18 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     for (String subPath : subPaths) {
       String nextPath = controllerStatusPath + "/" + subPath;
       List<String> subsubPaths = _gZkClient.getChildren(nextPath);
-      Assert.assertTrue(subsubPaths.size() == 0);
+      Assert.assertEquals(subsubPaths.size(), 0);
     }
 
     subPaths = _gZkClient.getChildren(instanceStatusPath);
-    Assert.assertTrue(subPaths.size() == 0);
+    Assert.assertEquals(subPaths.size(), 0);
     for (String subPath : subPaths) {
       String nextPath = instanceStatusPath + "/" + subPath;
       List<String> subsubPaths = _gZkClient.getChildren(nextPath);
       Assert.assertTrue(subsubPaths.size() > 0);
       for (String subsubPath : subsubPaths) {
         String nextnextPath = nextPath + "/" + subsubPath;
-        Assert.assertTrue(_gZkClient.getChildren(nextnextPath).size() == 0);
+        Assert.assertEquals(_gZkClient.getChildren(nextnextPath).size(), 0);
       }
     }
   }
@@ -330,8 +327,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     _factory._results.clear();
     HelixManager manager = null;
     for (int i = 0; i < NODE_NR; i++) {
-      _participants[i].getMessagingService().registerMessageHandlerFactory(
-          _factory.getMessageTypes(), _factory);
+      _participants[i].getMessagingService()
+          .registerMessageHandlerFactory(_factory.getMessageTypes(), _factory);
 
       manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager;
     }
@@ -377,9 +374,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     Thread.sleep(3000);
 
     Assert.assertEquals(0, _factory._results.size());
-    PropertyKey controllerTaskStatus =
-        keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(),
-            schedulerMessage.getMsgId());
+    PropertyKey controllerTaskStatus = keyBuilder
+        .controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), schedulerMessage.getMsgId());
     for (int i = 0; i < 10; i++) {
       StatusUpdate update = helixDataAccessor.getProperty(controllerTaskStatus);
       if (update == null || update.getRecord().getMapField("SentMessageCount") == null) {
@@ -387,7 +383,7 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       }
     }
     ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord();
-    Assert.assertTrue(statusUpdate.getMapField("SentMessageCount").get("MessageCount").equals("0"));
+    Assert.assertEquals(statusUpdate.getMapField("SentMessageCount").get("MessageCount"), "0");
     int count = 0;
     for (Set<String> val : _factory._results.values()) {
       count += val.size();
@@ -401,13 +397,13 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     Thread.sleep(2000);
     HelixManager manager = null;
     for (int i = 0; i < NODE_NR; i++) {
-      _participants[i].getMessagingService().registerMessageHandlerFactory(
-          _factory.getMessageTypes(), _factory);
+      _participants[i].getMessagingService()
+          .registerMessageHandlerFactory(_factory.getMessageTypes(), _factory);
 
-      _participants[i].getMessagingService().registerMessageHandlerFactory(
-          _factory.getMessageTypes(), _factory);
+      _participants[i].getMessagingService()
+          .registerMessageHandlerFactory(_factory.getMessageTypes(), _factory);
 
-      manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager;
+      manager = _participants[i];
     }
 
     Message schedulerMessage =
@@ -451,7 +447,7 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     cr2.setInstanceName("*");
     cr2.setSessionSpecific(false);
 
-    MockAsyncCallback callback = new MockAsyncCallback();
+    MockAsyncCallback callback;
     cr.setInstanceName("localhost_%");
     mapper = new ObjectMapper();
     serializationConfig = mapper.getSerializationConfig();
@@ -476,9 +472,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       crString = sw.toString();
       schedulerMessage.getRecord().setSimpleField("Criteria", crString);
       manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1);
-      String msgId =
-          callback._message.getResultMap().get(
-              DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID);
+      String msgId = callback._message.getResultMap()
+          .get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID);
 
       HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor();
       Builder keyBuilder = helixDataAccessor.keyBuilder();
@@ -497,8 +492,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       PropertyKey controllerTaskStatus =
           keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId);
       ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord();
-      Assert.assertTrue(statusUpdate.getMapField("SentMessageCount").get("MessageCount")
-          .equals("" + (_PARTITIONS * 3 / 5)));
+      Assert.assertEquals("" + (_PARTITIONS * 3 / 5),
+          statusUpdate.getMapField("SentMessageCount").get("MessageCount"));
       int messageResultCount = 0;
       for (String key : statusUpdate.getMapFields().keySet()) {
         if (key.startsWith("MessageResult")) {
@@ -508,12 +503,9 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       Assert.assertEquals(messageResultCount, _PARTITIONS * 3 / 5);
 
       int count = 0;
-      // System.out.println(i);
       for (Set<String> val : _factory._results.values()) {
-        // System.out.println(val);
         count += val.size();
       }
-      // System.out.println(count);
       Assert.assertEquals(count, _PARTITIONS * 3 / 5 * (i + 1));
     }
   }
@@ -523,13 +515,9 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     _factory._results.clear();
     HelixManager manager = null;
     for (int i = 0; i < NODE_NR; i++) {
-      _participants[i].getMessagingService().registerMessageHandlerFactory(
-          _factory.getMessageTypes(), _factory);
-
-      _participants[i].getMessagingService().registerMessageHandlerFactory(
-          _factory.getMessageTypes(), _factory);
-
-      manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager;
+      _participants[i].getMessagingService()
+          .registerMessageHandlerFactory(_factory.getMessageTypes(), _factory);
+      manager = _participants[i];
     }
 
     Message schedulerMessage =
@@ -573,7 +561,7 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     cr2.setInstanceName("*");
     cr2.setSessionSpecific(false);
 
-    Map<String, String> constraints = new TreeMap<String, String>();
+    Map<String, String> constraints = new TreeMap<>();
     constraints.put("MESSAGE_TYPE", "STATE_TRANSITION");
     constraints.put("TRANSITION", "OFFLINE-COMPLETED");
     constraints.put("CONSTRAINT_VALUE", "1");
@@ -593,13 +581,12 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     crString = sw.toString();
     schedulerMessage.getRecord().setSimpleField("Criteria", crString);
     manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1);
-    String msgIdPrime =
-        callback._message.getResultMap()
-            .get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID);
+    String msgIdPrime = callback._message.getResultMap()
+        .get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID);
 
     HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor();
     Builder keyBuilder = helixDataAccessor.keyBuilder();
-    ArrayList<String> msgIds = new ArrayList<String>();
+    ArrayList<String> msgIds = new ArrayList<>();
     for (int i = 0; i < NODE_NR; i++) {
       callback = new MockAsyncCallback();
       cr.setInstanceName("localhost_" + (START_PORT + i));
@@ -613,9 +600,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
       crString = sw.toString();
       schedulerMessage.getRecord().setSimpleField("Criteria", crString);
       manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1);
-      String msgId =
-          callback._message.getResultMap().get(
-              DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID);
+      String msgId = callback._message.getResultMap()
+          .get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID);
       msgIds.add(msgId);
     }
     for (int i = 0; i < NODE_NR; i++) {
@@ -626,26 +612,23 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
             keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId);
         ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord();
         if (statusUpdate.getMapFields().containsKey("Summary")) {
-          // System.err.println(msgId+" done");
           break;
         }
       }
 
+      // Add a half-second delay because it takes time for messages to be processed
+      Thread.sleep(500L);
       PropertyKey controllerTaskStatus =
           keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId);
       ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord();
-      Assert.assertTrue(statusUpdate.getMapField("SentMessageCount").get("MessageCount")
-          .equals("" + (_PARTITIONS * 3 / 5)));
+      Assert.assertEquals("" + (_PARTITIONS * 3 / 5),
+          statusUpdate.getMapField("SentMessageCount").get("MessageCount"));
       int messageResultCount = 0;
       for (String key : statusUpdate.getMapFields().keySet()) {
         if (key.startsWith("MessageResult")) {
           messageResultCount++;
         }
       }
-      if (messageResultCount != _PARTITIONS * 3 / 5) {
-        int x = 10;
-        x = x + messageResultCount;
-      }
       Assert.assertEquals(messageResultCount, _PARTITIONS * 3 / 5);
     }
 
@@ -660,10 +643,8 @@ public class TestSchedulerMessage extends ZkStandAloneCMTestBase {
     }
     int count = 0;
     for (Set<String> val : _factory._results.values()) {
-      // System.out.println(val);
       count += val.size();
     }
-    // System.out.println(count);
     Assert.assertEquals(count, _PARTITIONS * 3 * 2);
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalance.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalance.java
index 1fe333b..fd58d7f 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalance.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalance.java
@@ -47,7 +47,7 @@ import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
 public class TestCrushAutoRebalance extends ZkTestBase {
-  final int NUM_NODE = 6;
+  private final int NUM_NODE = 6;
   protected static final int START_PORT = 12918;
   protected static final int _PARTITIONS = 20;
 
@@ -62,7 +62,8 @@ public class TestCrushAutoRebalance extends ZkTestBase {
   Set<String> _allDBs = new HashSet<>();
   int _replica = 3;
 
-  String[] _testModels = { BuiltInStateModelDefinitions.OnlineOffline.name(),
+  String[] _testModels = {
+      BuiltInStateModelDefinitions.OnlineOffline.name(),
       BuiltInStateModelDefinitions.MasterSlave.name(),
       BuiltInStateModelDefinitions.LeaderStandby.name()
   };
@@ -87,8 +88,7 @@ public class TestCrushAutoRebalance extends ZkTestBase {
 
     // start dummy participants
     for (String node : _nodes) {
-      MockParticipantManager participant =
-          new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
+      MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
       participant.syncStart();
       _participants.add(participant);
     }
@@ -103,10 +103,15 @@ public class TestCrushAutoRebalance extends ZkTestBase {
   }
 
   @DataProvider(name = "rebalanceStrategies")
-  public static Object [][] rebalanceStrategies() {
-    return new String[][] { {"CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName()},
-        {"MultiRoundCrushRebalanceStrategy", MultiRoundCrushRebalanceStrategy.class.getName()},
-        {"CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()}
+  public static Object[][] rebalanceStrategies() {
+    return new String[][] {
+        {
+            "CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName()
+        }, {
+            "MultiRoundCrushRebalanceStrategy", MultiRoundCrushRebalanceStrategy.class.getName()
+        }, {
+            "CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()
+        }
     };
   }
 
@@ -130,7 +135,8 @@ public class TestCrushAutoRebalance extends ZkTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     for (String db : _allDBs) {
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       validateZoneAndTagIsolation(is, ev, _replica);
@@ -138,8 +144,8 @@ public class TestCrushAutoRebalance extends ZkTestBase {
   }
 
   @Test(dataProvider = "rebalanceStrategies")
-  public void testZoneIsolationWithInstanceTag(
-      String rebalanceStrategyName, String rebalanceStrategyClass) throws Exception {
+  public void testZoneIsolationWithInstanceTag(String rebalanceStrategyName,
+      String rebalanceStrategyClass) throws Exception {
     Set<String> tags = new HashSet<String>(_nodeToTagMap.values());
     int i = 0;
     for (String tag : tags) {
@@ -147,7 +153,8 @@ public class TestCrushAutoRebalance extends ZkTestBase {
       _gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS,
           BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO + "",
           rebalanceStrategyClass);
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       is.setInstanceGroupTag(tag);
       _gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, db, is);
       _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
@@ -161,14 +168,17 @@ public class TestCrushAutoRebalance extends ZkTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     for (String db : _allDBs) {
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       validateZoneAndTagIsolation(is, ev, _replica);
     }
   }
 
-  @Test (dependsOnMethods = { "testZoneIsolation", "testZoneIsolationWithInstanceTag"})
+  @Test(dependsOnMethods = {
+      "testZoneIsolation", "testZoneIsolationWithInstanceTag"
+  })
   public void testLackEnoughLiveRacks() throws Exception {
     System.out.println("TestLackEnoughInstances");
     enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
@@ -177,7 +187,7 @@ public class TestCrushAutoRebalance extends ZkTestBase {
     String zone = _nodeToZoneMap.values().iterator().next();
     for (int i = 0; i < _participants.size(); i++) {
       MockParticipantManager p = _participants.get(i);
-      if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)){
+      if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)) {
         p.syncStop();
       }
     }
@@ -197,14 +207,17 @@ public class TestCrushAutoRebalance extends ZkTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     for (String db : _allDBs) {
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       validateZoneAndTagIsolation(is, ev, 2);
     }
   }
 
-  @Test (dependsOnMethods = { "testLackEnoughLiveRacks"})
+  @Test(dependsOnMethods = {
+      "testLackEnoughLiveRacks"
+  })
   public void testLackEnoughRacks() throws Exception {
     System.out.println("TestLackEnoughInstances ");
     enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
@@ -213,10 +226,10 @@ public class TestCrushAutoRebalance extends ZkTestBase {
     String zone = _nodeToZoneMap.values().iterator().next();
     for (int i = 0; i < _participants.size(); i++) {
       MockParticipantManager p = _participants.get(i);
-      if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)){
+      if (_nodeToZoneMap.get(p.getInstanceName()).equals(zone)) {
         p.syncStop();
-        _gSetupTool.getClusterManagementTool()
-            .enableInstance(CLUSTER_NAME, p.getInstanceName(), false);
+        _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, p.getInstanceName(),
+            false);
         Thread.sleep(50);
         _gSetupTool.dropInstanceFromCluster(CLUSTER_NAME, p.getInstanceName());
       }
@@ -238,7 +251,8 @@ public class TestCrushAutoRebalance extends ZkTestBase {
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
     for (String db : _allDBs) {
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       validateZoneAndTagIsolation(is, ev, 2);
@@ -266,7 +280,7 @@ public class TestCrushAutoRebalance extends ZkTestBase {
       Map<String, String> assignmentMap = ev.getRecord().getMapField(partition);
       Set<String> instancesInEV = assignmentMap.keySet();
       // TODO: preference List is not persisted in IS.
-      //Assert.assertEquals(instancesInEV, instancesInIs);
+      // Assert.assertEquals(instancesInEV, instancesInIs);
       for (String instance : instancesInEV) {
         assignedZones.add(_nodeToZoneMap.get(instance));
         if (tag != null) {
@@ -281,27 +295,29 @@ public class TestCrushAutoRebalance extends ZkTestBase {
 
   @Test()
   public void testAddZone() throws Exception {
-    //TODO
+    // TODO
   }
 
   @Test()
   public void testAddNodes() throws Exception {
-    //TODO
+    // TODO
   }
 
   @Test()
   public void testNodeFailure() throws Exception {
-    //TODO
+    // TODO
   }
 
   @AfterClass
   public void afterClass() throws Exception {
-    /**
+    /*
      * shutdown order: 1) disconnect the controller 2) disconnect participants
      */
-    _controller.syncStop();
+    if (_controller != null && _controller.isConnected()) {
+      _controller.syncStop();
+    }
     for (MockParticipantManager p : _participants) {
-      if (p.isConnected()) {
+      if (p != null && p.isConnected()) {
         p.syncStop();
       }
     }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalanceNonRack.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalanceNonRack.java
index 9368700..ce4f1dd 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalanceNonRack.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestCrushAutoRebalanceNonRack.java
@@ -57,13 +57,14 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
   protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
   protected ClusterControllerManager _controller;
 
-  List<MockParticipantManager> _participants = new ArrayList<MockParticipantManager>();
-  Map<String, String> _nodeToTagMap = new HashMap<String, String>();
+  List<MockParticipantManager> _participants = new ArrayList<>();
+  Map<String, String> _nodeToTagMap = new HashMap<>();
   List<String> _nodes = new ArrayList<>();
-  Set<String> _allDBs = new HashSet<>();
-  int _replica = 3;
+  private Set<String> _allDBs = new HashSet<>();
+  private int _replica = 3;
 
-  private static String[] _testModels = { BuiltInStateModelDefinitions.OnlineOffline.name(),
+  private static String[] _testModels = {
+      BuiltInStateModelDefinitions.OnlineOffline.name(),
       BuiltInStateModelDefinitions.MasterSlave.name(),
       BuiltInStateModelDefinitions.LeaderStandby.name()
   };
@@ -106,14 +107,15 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
     _controller.syncStart();
 
     enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
-    //enableTopologyAwareRebalance(_gZkClient, CLUSTER_NAME, true);
   }
 
   @AfterClass
   public void afterClass() throws Exception {
-    _controller.syncStop();
+    if (_controller != null && _controller.isConnected()) {
+      _controller.syncStop();
+    }
     for (MockParticipantManager p : _participants) {
-      if (p.isConnected()) {
+      if (p != null && p.isConnected()) {
         p.syncStop();
       }
     }
@@ -123,8 +125,12 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
 
   @DataProvider(name = "rebalanceStrategies")
   public static String[][] rebalanceStrategies() {
-    return new String[][] { { "CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName() },
-        {"CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()}
+    return new String[][] {
+        {
+            "CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName()
+        }, {
+            "CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()
+        }
     };
   }
 
@@ -146,7 +152,8 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
             .setResources(_allDBs).build();
     Assert.assertTrue(_clusterVerifier.verify(5000));
     for (String db : _allDBs) {
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       validateIsolation(is, ev, _replica);
@@ -163,7 +170,8 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
       _gSetupTool.addResourceToCluster(CLUSTER_NAME, db, _PARTITIONS,
           BuiltInStateModelDefinitions.MasterSlave.name(), RebalanceMode.FULL_AUTO + "",
           rebalanceStrategyClass);
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       is.setInstanceGroupTag(tag);
       _gSetupTool.getClusterManagementTool().setResourceIdealState(CLUSTER_NAME, db, is);
       _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db, _replica);
@@ -176,7 +184,8 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
             .setResources(_allDBs).build();
     Assert.assertTrue(_clusterVerifier.verify(5000));
     for (String db : _allDBs) {
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       validateIsolation(is, ev, _replica);
@@ -211,7 +220,8 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
             .setResources(_allDBs).build();
     Assert.assertTrue(_clusterVerifier.verify(5000));
     for (String db : _allDBs) {
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       validateIsolation(is, ev, 2);
@@ -234,8 +244,8 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
     for (int i = 2; i < _participants.size(); i++) {
       MockParticipantManager p = _participants.get(i);
       p.syncStop();
-      _gSetupTool.getClusterManagementTool()
-          .enableInstance(CLUSTER_NAME, p.getInstanceName(), false);
+      _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, p.getInstanceName(),
+          false);
       _gSetupTool.dropInstanceFromCluster(CLUSTER_NAME, p.getInstanceName());
 
     }
@@ -254,7 +264,8 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
             .setResources(_allDBs).build();
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
     for (String db : _allDBs) {
-      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
+      IdealState is =
+          _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db);
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       validateIsolation(is, ev, 2);
@@ -304,6 +315,6 @@ public class TestCrushAutoRebalanceNonRack extends ZkStandAloneCMTestBase {
     }
     _allDBs.clear();
     // waiting for all DB be dropped.
-    Thread.sleep(200);
+    Thread.sleep(200L);
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestNodeSwap.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestNodeSwap.java
index 61e4d55..b71580e 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestNodeSwap.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/CrushRebalancers/TestNodeSwap.java
@@ -60,7 +60,8 @@ public class TestNodeSwap extends ZkTestBase {
   Set<String> _allDBs = new HashSet<>();
   int _replica = 3;
 
-  String[] _testModels = { BuiltInStateModelDefinitions.OnlineOffline.name(),
+  String[] _testModels = {
+      BuiltInStateModelDefinitions.OnlineOffline.name(),
       BuiltInStateModelDefinitions.MasterSlave.name(),
       BuiltInStateModelDefinitions.LeaderStandby.name()
   };
@@ -87,15 +88,14 @@ public class TestNodeSwap extends ZkTestBase {
       InstanceConfig instanceConfig =
           configAccessor.getInstanceConfig(CLUSTER_NAME, storageNodeName);
       instanceConfig.setDomain(domain);
-      _gSetupTool.getClusterManagementTool()
-          .setInstanceConfig(CLUSTER_NAME, storageNodeName, instanceConfig);
+      _gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, storageNodeName,
+          instanceConfig);
       nodes.add(storageNodeName);
     }
 
     // start dummy participants
     for (String node : nodes) {
-      MockParticipantManager participant =
-          new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
+      MockParticipantManager participant = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, node);
       participant.syncStart();
       _participants.add(participant);
     }
@@ -113,25 +113,27 @@ public class TestNodeSwap extends ZkTestBase {
   public void afterClass() throws Exception {
     _controller.syncStop();
     for (MockParticipantManager p : _participants) {
-      if (p.isConnected()) {
-        p.syncStop();
-      }
+      p.syncStop();
     }
     deleteCluster(CLUSTER_NAME);
   }
 
   @DataProvider(name = "rebalanceStrategies")
-  public static Object [][] rebalanceStrategies() {
-    return new String[][] { {"CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName()},
-        {"MultiRoundCrushRebalanceStrategy", MultiRoundCrushRebalanceStrategy.class.getName()},
-        {"CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()}
+  public static Object[][] rebalanceStrategies() {
+    return new String[][] {
+        {
+            "CrushRebalanceStrategy", CrushRebalanceStrategy.class.getName()
+        }, {
+            "MultiRoundCrushRebalanceStrategy", MultiRoundCrushRebalanceStrategy.class.getName()
+        }, {
+            "CrushEdRebalanceStrategy", CrushEdRebalanceStrategy.class.getName()
+        }
     };
   }
 
-
   @Test(dataProvider = "rebalanceStrategies")
-  public void testNodeSwap(String rebalanceStrategyName,
-      String rebalanceStrategyClass) throws Exception {
+  public void testNodeSwap(String rebalanceStrategyName, String rebalanceStrategyClass)
+      throws Exception {
     System.out.println("Test testNodeSwap for " + rebalanceStrategyName);
 
     int i = 0;
@@ -166,7 +168,8 @@ public class TestNodeSwap extends ZkTestBase {
         _gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, oldParticipantName);
     // disable the node first
     instanceConfig.setInstanceEnabled(false);
-    _gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, oldParticipantName, instanceConfig);
+    _gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, oldParticipantName,
+        instanceConfig);
     Assert.assertTrue(_clusterVerifier.verify(10000));
 
     // then remove it from topology
@@ -177,11 +180,10 @@ public class TestNodeSwap extends ZkTestBase {
     // 2. create new participant with same topology
     String newParticipantName = "RandomParticipant-" + rebalanceStrategyName + "_" + START_PORT;
     _gSetupTool.addInstanceToCluster(CLUSTER_NAME, newParticipantName);
-    InstanceConfig newConfig =
-        configAccessor.getInstanceConfig(CLUSTER_NAME, newParticipantName);
+    InstanceConfig newConfig = configAccessor.getInstanceConfig(CLUSTER_NAME, newParticipantName);
     newConfig.setDomain(instanceConfig.getDomainAsString());
-    _gSetupTool.getClusterManagementTool()
-        .setInstanceConfig(CLUSTER_NAME, newParticipantName, newConfig);
+    _gSetupTool.getClusterManagementTool().setInstanceConfig(CLUSTER_NAME, newParticipantName,
+        newConfig);
 
     MockParticipantManager participant =
         new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newParticipantName);
@@ -189,16 +191,15 @@ public class TestNodeSwap extends ZkTestBase {
     _participants.add(0, participant);
     Thread.sleep(2000);
 
-    _clusterVerifier =
-        new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
-            .setResources(_allDBs).build();
+    _clusterVerifier = new StrictMatchExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR)
+        .setResources(_allDBs).build();
     Assert.assertTrue(_clusterVerifier.verify(5000));
 
     for (String db : _allDBs) {
       ExternalView ev =
           _gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
       ExternalView oldEv = record.get(db);
-      for(String partition : ev.getPartitionSet()) {
+      for (String partition : ev.getPartitionSet()) {
         Map<String, String> stateMap = ev.getStateMap(partition);
         Map<String, String> oldStateMap = oldEv.getStateMap(partition);
         Assert.assertTrue(oldStateMap != null && stateMap != null);
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/DelayedAutoRebalancer/TestDelayedAutoRebalance.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/DelayedAutoRebalancer/TestDelayedAutoRebalance.java
index c3147ef..96a702e 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/DelayedAutoRebalancer/TestDelayedAutoRebalance.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/DelayedAutoRebalancer/TestDelayedAutoRebalance.java
@@ -54,7 +54,7 @@ public class TestDelayedAutoRebalance extends ZkTestBase {
   protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
   protected ClusterControllerManager _controller;
 
-  List<MockParticipantManager> _participants = new ArrayList<MockParticipantManager>();
+  List<MockParticipantManager> _participants = new ArrayList<>();
   int _replica = 3;
   int _minActiveReplica = _replica - 1;
   ZkHelixClusterVerifier _clusterVerifier;
@@ -320,8 +320,8 @@ public class TestDelayedAutoRebalance extends ZkTestBase {
 
   @AfterClass
   public void afterClass() throws Exception {
-    /**
-     * shutdown order: 1) disconnect the controller 2) disconnect participants
+    /*
+      shutdown order: 1) disconnect the controller 2) disconnect participants
      */
     _controller.syncStop();
     for (MockParticipantManager participant : _participants) {
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalance.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalance.java
index 0042754..e7d0b71 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalance.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalance.java
@@ -43,19 +43,23 @@ import org.apache.helix.tools.ClusterSetup;
 import org.apache.helix.tools.ClusterStateVerifier;
 import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier;
 import org.testng.Assert;
+import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 public class TestAutoRebalance extends ZkStandAloneCMTestBase {
-  String db2 = TEST_DB + "2";
-  String _tag = "SSDSSD";
+  private String db2 = TEST_DB + "2";
+  private String _tag = "SSDSSD";
+  private Set<MockParticipantManager> _extraParticipants;
 
   @Override
   @BeforeClass
   public void beforeClass() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
 
+    // Cache references to mock participants for teardown
+    _extraParticipants = new HashSet<>();
+
     // setup storage cluster
     _gSetupTool.addCluster(CLUSTER_NAME, true);
     _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL,
@@ -92,14 +96,22 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
     _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
     _controller.syncStart();
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, TEST_DB));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
 
     Assert.assertTrue(result);
 
   }
 
+  @Override
+  @AfterClass
+  public void afterClass() throws Exception {
+    for (MockParticipantManager participantManager : _extraParticipants) {
+      participantManager.syncStop();
+    }
+    super.afterClass();
+  }
+
   @Test()
   public void testDropResourceAutoRebalance() throws Exception {
     // add a resource to be dropped
@@ -108,17 +120,17 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
 
     _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "MyDB", 1);
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, "MyDB"));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, "MyDB"));
     Assert.assertTrue(result);
 
     String command = "-zkSvr " + ZK_ADDR + " -dropResource " + CLUSTER_NAME + " " + "MyDB";
     ClusterSetup.processCommandLineArgs(command.split(" "));
 
     TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 30 * 1000, CLUSTER_NAME, "MyDB",
-        TestHelper.<String>setOf("localhost_12918", "localhost_12919", "localhost_12920",
-            "localhost_12921", "localhost_12922"), ZK_ADDR);
+        TestHelper.setOf("localhost_12918", "localhost_12919", "localhost_12920", "localhost_12921",
+            "localhost_12922"),
+        ZK_ADDR);
 
     // add a resource to be dropped
     _gSetupTool.addResourceToCluster(CLUSTER_NAME, "MyDB2", _PARTITIONS, "MasterSlave",
@@ -126,17 +138,17 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
 
     _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, "MyDB2", 1);
 
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, "MyDB2"));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, "MyDB2"));
     Assert.assertTrue(result);
 
     command = "-zkSvr " + ZK_ADDR + " -dropResource " + CLUSTER_NAME + " " + "MyDB2";
     ClusterSetup.processCommandLineArgs(command.split(" "));
 
     TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 30 * 1000, CLUSTER_NAME, "MyDB2",
-        TestHelper.<String>setOf("localhost_12918", "localhost_12919", "localhost_12920",
-            "localhost_12921", "localhost_12922"), ZK_ADDR);
+        TestHelper.setOf("localhost_12918", "localhost_12919", "localhost_12920", "localhost_12921",
+            "localhost_12922"),
+        ZK_ADDR);
   }
 
   @Test()
@@ -144,9 +156,8 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
     // kill 1 node
     _participants[0].syncStop();
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, TEST_DB));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
     Assert.assertTrue(result);
 
     // add 2 nodes
@@ -156,28 +167,25 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
 
       MockParticipantManager participant =
           new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, storageNodeName.replace(':', '_'));
+      _extraParticipants.add(participant);
       participant.syncStart();
     }
     Thread.sleep(100);
-    result =
-        ClusterStateVerifier.verifyByPolling(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, TEST_DB), 10000, 100);
+    result = ClusterStateVerifier.verifyByPolling(
+        new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB), 10000, 100);
     Assert.assertTrue(result);
 
-    result =
-        ClusterStateVerifier.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, db2));
+    result = ClusterStateVerifier
+        .verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, db2));
     Assert.assertTrue(result);
     HelixDataAccessor accessor =
-        new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+        new ZKHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<>(_gZkClient));
     Builder keyBuilder = accessor.keyBuilder();
     ExternalView ev = accessor.getProperty(keyBuilder.externalView(db2));
-    Set<String> instancesSet = new HashSet<String>();
+    Set<String> instancesSet = new HashSet<>();
     for (String partitionName : ev.getRecord().getMapFields().keySet()) {
       Map<String, String> assignmentMap = ev.getRecord().getMapField(partitionName);
-      for (String instance : assignmentMap.keySet()) {
-        instancesSet.add(instance);
-      }
+      instancesSet.addAll(assignmentMap.keySet());
     }
     Assert.assertEquals(instancesSet.size(), 2);
   }
@@ -187,7 +195,7 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
     if (externalView == null) {
       return false;
     }
-    Map<String, Integer> masterPartitionsCountMap = new HashMap<String, Integer>();
+    Map<String, Integer> masterPartitionsCountMap = new HashMap<>();
     for (String partitionName : externalView.getMapFields().keySet()) {
       Map<String, String> assignmentMap = externalView.getMapField(partitionName);
       // Assert.assertTrue(assignmentMap.size() >= replica);
@@ -207,7 +215,8 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
     for (String instanceName : masterPartitionsCountMap.keySet()) {
       int instancePartitionCount = masterPartitionsCountMap.get(instanceName);
       totalCount += instancePartitionCount;
-      if (!(instancePartitionCount == perInstancePartition || instancePartitionCount == perInstancePartition + 1)) {
+      if (!(instancePartitionCount == perInstancePartition
+          || instancePartitionCount == perInstancePartition + 1)) {
         return false;
       }
       if (instancePartitionCount == perInstancePartition + 1) {
@@ -216,11 +225,7 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
         }
       }
     }
-    if (partitionCount != totalCount) {
-      return false;
-    }
-    return true;
-
+    return partitionCount == totalCount;
   }
 
   public static class ExternalViewBalancedVerifier implements ZkVerifier {
@@ -228,7 +233,8 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
     String _resourceName;
     HelixZkClient _client;
 
-    public ExternalViewBalancedVerifier(HelixZkClient client, String clusterName, String resourceName) {
+    public ExternalViewBalancedVerifier(HelixZkClient client, String clusterName,
+        String resourceName) {
       _clusterName = clusterName;
       _resourceName = resourceName;
       _client = client;
@@ -237,13 +243,12 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
     @Override
     public boolean verify() {
       HelixDataAccessor accessor =
-          new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+          new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<>(_gZkClient));
       Builder keyBuilder = accessor.keyBuilder();
       int numberOfPartitions;
       try {
-        numberOfPartitions =
-            accessor.getProperty(keyBuilder.idealStates(_resourceName)).getRecord().getListFields()
-                .size();
+        numberOfPartitions = accessor.getProperty(keyBuilder.idealStates(_resourceName)).getRecord()
+            .getListFields().size();
       } catch (Exception e) {
         return false;
       }
@@ -284,6 +289,5 @@ public class TestAutoRebalance extends ZkStandAloneCMTestBase {
     public String getClusterName() {
       return _clusterName;
     }
-
   }
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalancePartitionLimit.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalancePartitionLimit.java
index 37ee655..34e374d 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalancePartitionLimit.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalancePartitionLimit.java
@@ -38,20 +38,15 @@ import org.apache.helix.model.ExternalView;
 import org.apache.helix.model.IdealState.RebalanceMode;
 import org.apache.helix.tools.ClusterStateVerifier;
 import org.apache.helix.tools.ClusterStateVerifier.ZkVerifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.Assert;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
-  private static final Logger LOG = LoggerFactory.getLogger(TestAutoRebalancePartitionLimit.class
-      .getName());
 
   @Override
   @BeforeClass
   public void beforeClass() throws Exception {
-    // Logger.getRootLogger().setLevel(Level.INFO);
     System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
 
     // setup storage cluster
@@ -70,21 +65,20 @@ public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
     _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
     _controller.syncStart();
 
-    HelixManager manager = _controller; // _startCMResultMap.get(controllerName)._manager;
+    HelixManager manager = _controller;
     HelixDataAccessor accessor = manager.getHelixDataAccessor();
+
     // start dummy participants
     for (int i = 0; i < NODE_NR; i++) {
       String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
       _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName);
       _participants[i].syncStart();
       Thread.sleep(100);
-      boolean result =
-          ClusterStateVerifier.verifyByPolling(new ExternalViewBalancedVerifier(_gZkClient,
-              CLUSTER_NAME, TEST_DB), 10000, 100);
+      boolean result = ClusterStateVerifier.verifyByPolling(
+          new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB), 10000, 100);
       Assert.assertTrue(result);
       ExternalView ev =
           manager.getHelixDataAccessor().getProperty(accessor.keyBuilder().externalView(TEST_DB));
-      System.out.println(ev.getPartitionSet().size());
       if (i < 3) {
         Assert.assertEquals(ev.getPartitionSet().size(), 25 * (i + 1));
       } else {
@@ -92,23 +86,20 @@ public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
       }
     }
 
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, TEST_DB));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
 
     Assert.assertTrue(result);
   }
 
   @Test()
-  public void testAutoRebalanceWithMaxPartitionPerNode() throws Exception {
+  public void testAutoRebalanceWithMaxPartitionPerNode() {
     HelixManager manager = _controller;
     // kill 1 node
     _participants[0].syncStop();
 
-    // verifyBalanceExternalView();
-    boolean result =
-        ClusterStateVerifier.verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, TEST_DB));
+    boolean result = ClusterStateVerifier
+        .verifyByZkCallback(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
     Assert.assertTrue(result);
     HelixDataAccessor accessor = manager.getHelixDataAccessor();
     ExternalView ev =
@@ -117,15 +108,14 @@ public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
 
     _participants[1].syncStop();
 
-    // verifyBalanceExternalView();
-    result =
-        ClusterStateVerifier.verifyByPolling(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, TEST_DB));
+    result = ClusterStateVerifier
+        .verifyByPolling(new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB));
     Assert.assertTrue(result);
     ev = manager.getHelixDataAccessor().getProperty(accessor.keyBuilder().externalView(TEST_DB));
     Assert.assertEquals(ev.getPartitionSet().size(), 75);
 
     // add 2 nodes
+    MockParticipantManager[] newParticipants = new MockParticipantManager[2];
     for (int i = 0; i < 2; i++) {
       String storageNodeName = PARTICIPANT_PREFIX + "_" + (1000 + i);
       _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
@@ -133,22 +123,26 @@ public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
       String newInstanceName = storageNodeName.replace(':', '_');
       MockParticipantManager participant =
           new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, newInstanceName);
+      newParticipants[i] = participant;
       participant.syncStart();
     }
 
-    Thread.sleep(100);
-    result =
-        ClusterStateVerifier.verifyByPolling(new ExternalViewBalancedVerifier(_gZkClient,
-            CLUSTER_NAME, TEST_DB), 10000, 100);
-    Assert.assertTrue(result);
+    Assert.assertTrue(ClusterStateVerifier.verifyByPolling(
+        new ExternalViewBalancedVerifier(_gZkClient, CLUSTER_NAME, TEST_DB), 10000, 100));
+
+    // Clean up the extra mock participants
+    for (MockParticipantManager participant : newParticipants) {
+      if (participant != null && participant.isConnected()) {
+        participant.syncStop();
+      }
+    }
   }
 
-  static boolean verifyBalanceExternalView(ZNRecord externalView, int partitionCount,
+  private static boolean verifyBalanceExternalView(ZNRecord externalView, int partitionCount,
       String masterState, int replica, int instances, int maxPerInstance) {
-    Map<String, Integer> masterPartitionsCountMap = new HashMap<String, Integer>();
+    Map<String, Integer> masterPartitionsCountMap = new HashMap<>();
     for (String partitionName : externalView.getMapFields().keySet()) {
       Map<String, String> assignmentMap = externalView.getMapField(partitionName);
-      // Assert.assertTrue(assignmentMap.size() >= replica);
       for (String instance : assignmentMap.keySet()) {
         if (assignmentMap.get(instance).equals(masterState)) {
           if (!masterPartitionsCountMap.containsKey(instance)) {
@@ -166,7 +160,8 @@ public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
       int instancePartitionCount = masterPartitionsCountMap.get(instanceName);
       totalCount += instancePartitionCount;
       if (!(instancePartitionCount == perInstancePartition
-          || instancePartitionCount == perInstancePartition + 1 || instancePartitionCount == maxPerInstance)) {
+          || instancePartitionCount == perInstancePartition + 1
+          || instancePartitionCount == maxPerInstance)) {
         return false;
       }
       if (instancePartitionCount == maxPerInstance) {
@@ -181,11 +176,7 @@ public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
     if (totalCount == maxPerInstance * instances) {
       return true;
     }
-    if (partitionCount != totalCount) {
-      return false;
-    }
-    return true;
-
+    return partitionCount == totalCount;
   }
 
   public static class ExternalViewBalancedVerifier implements ZkVerifier {
@@ -193,7 +184,7 @@ public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
     String _resourceName;
     HelixZkClient _client;
 
-    public ExternalViewBalancedVerifier(HelixZkClient client, String clusterName, String resourceName) {
+    ExternalViewBalancedVerifier(HelixZkClient client, String clusterName, String resourceName) {
       _clusterName = clusterName;
       _resourceName = resourceName;
       _client = client;
@@ -202,19 +193,19 @@ public class TestAutoRebalancePartitionLimit extends ZkStandAloneCMTestBase {
     @Override
     public boolean verify() {
       HelixDataAccessor accessor =
-          new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));
+          new ZKHelixDataAccessor(_clusterName, new ZkBaseDataAccessor<>(_gZkClient));
       Builder keyBuilder = accessor.keyBuilder();
-      int numberOfPartitions =
-          accessor.getProperty(keyBuilder.idealStates(_resourceName)).getRecord().getListFields()
-              .size();
+      int numberOfPartitions = accessor.getProperty(keyBuilder.idealStates(_resourceName))
+          .getRecord().getListFields().size();
       ResourceControllerDataProvider cache = new ResourceControllerDataProvider();
       cache.refresh(accessor);
       String masterValue =
           cache.getStateModelDef(cache.getIdealState(_resourceName).getStateModelDefRef())
               .getStatesPriorityList().get(0);
       int replicas = Integer.parseInt(cache.getIdealState(_resourceName).getReplicas());
-      return verifyBalanceExternalView(accessor.getProperty(keyBuilder.externalView(_resourceName))
-          .getRecord(), numberOfPartitions, masterValue, replicas, cache.getLiveInstances().size(),
+      return verifyBalanceExternalView(
+          accessor.getProperty(keyBuilder.externalView(_resourceName)).getRecord(),
+          numberOfPartitions, masterValue, replicas, cache.getLiveInstances().size(),
           cache.getIdealState(_resourceName).getMaxPartitionsPerInstance());
     }
 
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalanceWithDisabledInstance.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalanceWithDisabledInstance.java
index 60df196..3f99b27 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalanceWithDisabledInstance.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestAutoRebalanceWithDisabledInstance.java
@@ -20,16 +20,13 @@ package org.apache.helix.integration.rebalancer;
  */
 
 import java.util.HashSet;
-import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import org.apache.helix.HelixAdmin;
 import org.apache.helix.integration.common.ZkStandAloneCMTestBase;
 import org.apache.helix.integration.manager.MockParticipantManager;
 import org.apache.helix.model.ExternalView;
-import org.apache.helix.model.IdealState;
 import org.apache.helix.model.IdealState.RebalanceMode;
-import org.apache.helix.tools.ClusterStateVerifier;
 import org.testng.Assert;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
@@ -42,113 +39,87 @@ public class TestAutoRebalanceWithDisabledInstance extends ZkStandAloneCMTestBas
   public void beforeClass() throws Exception {
     super.beforeClass();
     _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB_2, _PARTITIONS, STATE_MODEL,
-        RebalanceMode.FULL_AUTO + "");
+        RebalanceMode.FULL_AUTO.name());
     _gSetupTool.rebalanceResource(CLUSTER_NAME, TEST_DB_2, _replica);
 
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
   }
 
   @Test()
-  public void testDisableEnableInstanceAutoRebalance() throws Exception {
+  public void testDisableEnableInstanceAutoRebalance() throws InterruptedException {
     String disabledInstance = _participants[0].getInstanceName();
 
-    // TODO: preference list is not persisted in IS for full-auto,
-    // Need a way to find how helix assigns partitions to nodes.
-    /*
-    Set<String> assignedPartitions = getPartitionsAssignedtoInstance(CLUSTER_NAME, TEST_DB_2,
-        disabledInstance);
-    Assert.assertFalse(assignedPartitions.isEmpty());
-    */
-
-    Set<String> currentPartitions = getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2,
-        disabledInstance);
+    Set<String> currentPartitions =
+        getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, disabledInstance);
     Assert.assertFalse(currentPartitions.isEmpty());
 
     // disable instance
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, disabledInstance, false);
+    // check that the instance is really disabled
+    if (_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, disabledInstance)
+        .getInstanceEnabled()) {
+      Thread.sleep(2000L);
+    }
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
-    // TODO: preference list is not persisted in IS for full-auto,
-    // Need a way to find how helix assigns partitions to nodes.
-    /*
-    assignedPartitions = getPartitionsAssignedtoInstance(CLUSTER_NAME, TEST_DB_2, disabledInstance);
-    Assert.assertTrue(assignedPartitions.isEmpty());
-    */
-
     currentPartitions = getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, disabledInstance);
     Assert.assertTrue(currentPartitions.isEmpty());
 
-    //enable instance
+    // enable instance
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, disabledInstance, true);
+    // check that the instance is really enabled
+    if (!_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, disabledInstance)
+        .getInstanceEnabled()) {
+      Thread.sleep(2000L);
+    }
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
-
-    // TODO: preference list is not persisted in IS for full-auto,
-    // Need a way to find how helix assigns partitions to nodes.
-    /*
-    assignedPartitions = getPartitionsAssignedtoInstance(CLUSTER_NAME, TEST_DB_2, disabledInstance);
-    Assert.assertFalse(assignedPartitions.isEmpty());
-    */
-
     currentPartitions = getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, disabledInstance);
     Assert.assertFalse(currentPartitions.isEmpty());
   }
 
   @Test()
-  public void testAddDisabledInstanceAutoRebalance() throws Exception {
+  public void testAddDisabledInstanceAutoRebalance() throws InterruptedException {
     // add disabled instance.
     String nodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + NODE_NR);
     _gSetupTool.addInstanceToCluster(CLUSTER_NAME, nodeName);
     MockParticipantManager participant =
-          new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, nodeName);
+        new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, nodeName);
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, nodeName, false);
+    // check that the instance is really disabled
+    if (_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, nodeName)
+        .getInstanceEnabled()) {
+      Thread.sleep(2000L);
+    }
 
     participant.syncStart();
 
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
-    // TODO: preference list is not persisted in IS for full-auto,
-    // Need a way to find how helix assigns partitions to nodes.
-    /*
-    Set<String> assignedPartitions = getPartitionsAssignedtoInstance(CLUSTER_NAME, TEST_DB_2, nodeName);
-    Assert.assertTrue(assignedPartitions.isEmpty());
-    */
-    Set<String> currentPartitions = getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2,
-        nodeName);
+
+    Set<String> currentPartitions =
+        getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, nodeName);
     Assert.assertTrue(currentPartitions.isEmpty());
 
-    //enable instance
+    // enable instance
     _gSetupTool.getClusterManagementTool().enableInstance(CLUSTER_NAME, nodeName, true);
+    // check that the instance is really enabled
+    if (!_gSetupTool.getClusterManagementTool().getInstanceConfig(CLUSTER_NAME, nodeName)
+        .getInstanceEnabled()) {
+      Thread.sleep(2000L);
+    }
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
-    // TODO: preference list is not persisted in IS for full-auto,
-    // Need a way to find how helix assigns partitions to nodes.
-    /*
-    assignedPartitions = getPartitionsAssignedtoInstance(CLUSTER_NAME, TEST_DB_2, nodeName);
-    Assert.assertFalse(assignedPartitions.isEmpty());
-    */
 
     currentPartitions = getCurrentPartitionsOnInstance(CLUSTER_NAME, TEST_DB_2, nodeName);
     Assert.assertFalse(currentPartitions.isEmpty());
-  }
 
-  private Set<String> getPartitionsAssignedtoInstance(String cluster, String dbName, String instance) {
-    HelixAdmin admin = _gSetupTool.getClusterManagementTool();
-    Set<String> partitionSet = new HashSet<String>();
-    IdealState is = admin.getResourceIdealState(cluster, dbName);
-    for (String partition : is.getRecord().getListFields().keySet()) {
-      List<String> assignments = is.getRecord().getListField(partition);
-      for (String ins : assignments) {
-        if (ins.equals(instance)) {
-          partitionSet.add(partition);
-        }
-      }
-    }
-
-    return partitionSet;
+    // Kill the newly added MockParticipant so that the cluster could be cleaned up
+    participant.syncStop();
   }
 
-  private Set<String> getCurrentPartitionsOnInstance(String cluster, String dbName, String instance) {
+  private Set<String> getCurrentPartitionsOnInstance(String cluster, String dbName,
+      String instance) {
     HelixAdmin admin = _gSetupTool.getClusterManagementTool();
-    Set<String> partitionSet = new HashSet<String>();
+    Set<String> partitionSet = new HashSet<>();
 
     ExternalView ev = admin.getResourceExternalView(cluster, dbName);
     for (String partition : ev.getRecord().getMapFields().keySet()) {
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingMaxPartition.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingMaxPartition.java
index 7cd0235..e05f017 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingMaxPartition.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingMaxPartition.java
@@ -39,7 +39,7 @@ import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 public class TestClusterInMaintenanceModeWhenReachingMaxPartition extends ZkTestBase {
-  final int NUM_NODE = 5;
+  private final int NUM_NODE = 5;
   protected static final int START_PORT = 12918;
   protected static final int _PARTITIONS = 5;
 
@@ -47,11 +47,10 @@ public class TestClusterInMaintenanceModeWhenReachingMaxPartition extends ZkTest
   protected final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
   protected ClusterControllerManager _controller;
 
-  List<MockParticipantManager> _participants = new ArrayList<MockParticipantManager>();
-  int _replica = 3;
-  ZkHelixClusterVerifier _clusterVerifier;
-  List<String> _testDBs = new ArrayList<String>();
-  HelixDataAccessor _dataAccessor;
+  private List<MockParticipantManager> _participants = new ArrayList<>();
+  private ZkHelixClusterVerifier _clusterVerifier;
+  private List<String> _testDBs = new ArrayList<>();
+  private HelixDataAccessor _dataAccessor;
 
   @BeforeClass
   public void beforeClass() throws Exception {
@@ -82,7 +81,7 @@ public class TestClusterInMaintenanceModeWhenReachingMaxPartition extends ZkTest
     _dataAccessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
   }
 
-  protected String[] TestStateModels = {
+  private String[] TestStateModels = {
       BuiltInStateModelDefinitions.MasterSlave.name(),
       BuiltInStateModelDefinitions.OnlineOffline.name(),
       BuiltInStateModelDefinitions.LeaderStandby.name()
@@ -98,14 +97,16 @@ public class TestClusterInMaintenanceModeWhenReachingMaxPartition extends ZkTest
     int i = 0;
     for (String stateModel : TestStateModels) {
       String db = "Test-DB-" + i++;
-      createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, _replica,
-          _replica, -1);
+      int replica = 3;
+      createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, _PARTITIONS, replica,
+          replica, -1);
       _testDBs.add(db);
     }
     Thread.sleep(100L);
     Assert.assertTrue(_clusterVerifier.verifyByPolling());
 
-    MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
+    MaintenanceSignal maintenanceSignal =
+        _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
     Assert.assertNull(maintenanceSignal);
 
     for (i = 2; i < NUM_NODE; i++) {
@@ -120,14 +121,12 @@ public class TestClusterInMaintenanceModeWhenReachingMaxPartition extends ZkTest
 
   @AfterClass
   public void afterClass() throws Exception {
-    /**
+    /*
      * shutdown order: 1) disconnect the controller 2) disconnect participants
      */
     _controller.syncStop();
     for (MockParticipantManager participant : _participants) {
-      if (participant.isConnected()) {
-        participant.syncStop();
-      }
+      participant.syncStop();
     }
     deleteCluster(CLUSTER_NAME);
     System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit.java
index 9067bb5..5c68aaa 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit.java
@@ -50,19 +50,17 @@ import org.testng.annotations.Test;
 import static org.apache.helix.monitoring.mbeans.ClusterStatusMonitor.CLUSTER_DN_KEY;
 import static org.apache.helix.util.StatusUpdateUtil.ErrorType.RebalanceResourceFailure;
 
-public class TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit
-    extends ZkTestBase {
-  static final int NUM_NODE = 10;
-  static final int START_PORT = 12918;
-  static final int _PARTITIONS = 5;
+public class TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit extends ZkTestBase {
+  private static final int NUM_NODE = 10;
+  private static final int START_PORT = 12918;
+  private static final int _PARTITIONS = 5;
   private static final MBeanServerConnection _server = ManagementFactory.getPlatformMBeanServer();
 
-  final String CLASS_NAME = getShortClassName();
-  final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
+  private final String CLASS_NAME = getShortClassName();
+  private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
   private ClusterControllerManager _controller;
 
-  private List<MockParticipantManager> _participants = new ArrayList<MockParticipantManager>();
-  private ZkHelixClusterVerifier _clusterVerifier;
+  private List<MockParticipantManager> _participants = new ArrayList<>();
   private HelixDataAccessor _dataAccessor;
   private int _maxOfflineInstancesAllowed = 4;
 
@@ -88,7 +86,7 @@ public class TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit
     _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
     _controller.syncStart();
 
-    _clusterVerifier =
+    ZkHelixClusterVerifier clusterVerifier =
         new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR).build();
 
     enablePersistBestPossibleAssignment(_gZkClient, CLUSTER_NAME, true);
@@ -105,7 +103,7 @@ public class TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit
           BuiltInStateModelDefinitions.MasterSlave.name(), _PARTITIONS, 3, 3, -1);
     }
     Thread.sleep(100);
-    Assert.assertTrue(_clusterVerifier.verifyByPolling());
+    Assert.assertTrue(clusterVerifier.verifyByPolling());
   }
 
   @AfterMethod
@@ -152,8 +150,7 @@ public class TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit
     admin.enableMaintenanceMode(CLUSTER_NAME, false);
   }
 
-
-  @Test (dependsOnMethods = "testWithDisabledInstancesLimit")
+  @Test(dependsOnMethods = "testWithDisabledInstancesLimit")
   public void testWithOfflineInstancesLimit() throws Exception {
     MaintenanceSignal maintenanceSignal =
         _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance());
@@ -184,33 +181,29 @@ public class TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit
 
   @AfterClass
   public void afterClass() throws Exception {
-    /**
+    /*
      * shutdown order: 1) disconnect the controller 2) disconnect participants
      */
     _controller.syncStop();
     for (MockParticipantManager participant : _participants) {
-      if (participant.isConnected()) {
-        participant.syncStop();
-      }
+      participant.syncStop();
     }
     deleteCluster(CLUSTER_NAME);
     System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
   }
 
   private void checkForRebalanceError(final boolean expectError) throws Exception {
-    boolean result = TestHelper.verify(new TestHelper.Verifier() {
-      @Override
-      public boolean verify() throws Exception {
-        /* TODO re-enable this check when we start recording rebalance error again
-        ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
-        PropertyKey errorNodeKey =
-            accessor.keyBuilder().controllerTaskError(RebalanceResourceFailure.name());
-        Assert.assertEquals(accessor.getProperty(errorNodeKey) != null, expectError);
-        */
-        Long value =
-            (Long) _server.getAttribute(getClusterMbeanName(CLUSTER_NAME), "RebalanceFailureGauge");
-        return expectError == (value != null && value.longValue() > 0);
-      }
+    boolean result = TestHelper.verify(() -> {
+      /*
+       * TODO re-enable this check when we start recording rebalance error again
+       * ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(CLUSTER_NAME, _baseAccessor);
+       * PropertyKey errorNodeKey =
+       * accessor.keyBuilder().controllerTaskError(RebalanceResourceFailure.name());
+       * Assert.assertEquals(accessor.getProperty(errorNodeKey) != null, expectError);
+       */
+      Long value =
+          (Long) _server.getAttribute(getClusterMbeanName(CLUSTER_NAME), "RebalanceFailureGauge");
+      return expectError == (value != null && value > 0);
     }, 5000);
     Assert.assertTrue(result);
   }
@@ -222,10 +215,8 @@ public class TestClusterInMaintenanceModeWhenReachingOfflineInstancesLimit
     accessor.removeProperty(errorNodeKey);
   }
 
-  private ObjectName getClusterMbeanName(String clusterName)
-      throws MalformedObjectNameException {
-    String clusterBeanName =
-        String.format("%s=%s", CLUSTER_DN_KEY, clusterName);
+  private ObjectName getClusterMbeanName(String clusterName) throws MalformedObjectNameException {
+    String clusterBeanName = String.format("%s=%s", CLUSTER_DN_KEY, clusterName);
     return new ObjectName(
         String.format("%s:%s", MonitorDomainNames.ClusterStatus.name(), clusterBeanName));
   }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestCustomIdealState.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestCustomIdealState.java
index 7002cf9..a8e1f92 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestCustomIdealState.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestCustomIdealState.java
@@ -24,13 +24,9 @@ import org.apache.helix.TestHelper;
 import org.apache.helix.common.ZkTestBase;
 import org.apache.helix.integration.TestDriver;
 import org.apache.helix.tools.ClusterSetup;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
 
 public class TestCustomIdealState extends ZkTestBase {
-  private static Logger LOG = LoggerFactory.getLogger(TestCustomIdealState.class);
-
   @Test
   public void testBasic() throws Exception {
 
@@ -39,9 +35,8 @@ public class TestCustomIdealState extends ZkTestBase {
     int numInstance = 5;
     int replica = 3;
 
-    String uniqClusterName =
-        "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource + "_n"
-            + numInstance + "_r" + replica + "_basic";
+    String uniqClusterName = "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource
+        + "_n" + numInstance + "_r" + replica + "_basic";
     System.out.println("START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
 
     TestDriver.setupClusterWithoutRebalance(uniqClusterName, ZK_ADDR, numResources,
@@ -57,6 +52,7 @@ public class TestCustomIdealState extends ZkTestBase {
 
     TestDriver.stopCluster(uniqClusterName);
 
+    deleteCluster(uniqClusterName);
     System.out.println("STOP " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
   }
 
@@ -67,9 +63,8 @@ public class TestCustomIdealState extends ZkTestBase {
     int numInstance = 5;
     int replica = 3;
 
-    String uniqClusterName =
-        "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource + "_n"
-            + numInstance + "_r" + replica + "_nonalive";
+    String uniqClusterName = "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource
+        + "_n" + numInstance + "_r" + replica + "_nonalive";
     System.out.println("START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
 
     TestDriver.setupClusterWithoutRebalance(uniqClusterName, ZK_ADDR, numResources,
@@ -94,8 +89,8 @@ public class TestCustomIdealState extends ZkTestBase {
 
     TestDriver.stopCluster(uniqClusterName);
 
+    deleteCluster(uniqClusterName);
     System.out.println("STOP " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
-
   }
 
   @Test()
@@ -105,9 +100,8 @@ public class TestCustomIdealState extends ZkTestBase {
     int numInstance = 5;
     int replica = 3;
 
-    String uniqClusterName =
-        "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource + "_n"
-            + numInstance + "_r" + replica + "_drop";
+    String uniqClusterName = "TestCustomIS_" + "rg" + numResources + "_p" + numPartitionsPerResource
+        + "_n" + numInstance + "_r" + replica + "_drop";
 
     System.out.println("START " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
     TestDriver.setupClusterWithoutRebalance(uniqClusterName, ZK_ADDR, numResources,
@@ -125,13 +119,12 @@ public class TestCustomIdealState extends ZkTestBase {
     setup.dropResourceFromCluster(uniqClusterName, "TestDB0");
 
     TestHelper.verifyWithTimeout("verifyEmptyCurStateAndExtView", 30 * 1000, uniqClusterName,
-        "TestDB0", TestHelper.<String> setOf("localhost_12918", "localhost_12919",
-            "localhost_12920", "localhost_12921", "localhost_12922"), ZK_ADDR);
+        "TestDB0", TestHelper.setOf("localhost_12918", "localhost_12919",
+            "localhost_12920", "localhost_12921", "localhost_12922"),
+        ZK_ADDR);
 
     TestDriver.stopCluster(uniqClusterName);
+    deleteCluster(uniqClusterName);
     System.out.println("STOP " + uniqClusterName + " at " + new Date(System.currentTimeMillis()));
   }
-
-  // TODO add a test case that verify (in case of node failure) best possible
-  // state is a subset of ideal state
 }
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestSemiAutoRebalance.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestSemiAutoRebalance.java
index ac4a951..b98d75b 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestSemiAutoRebalance.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestSemiAutoRebalance.java
@@ -57,10 +57,9 @@ public class TestSemiAutoRebalance extends ZkTestBase {
   protected PropertyKey.Builder _keyBuilder;
 
   @BeforeClass
-  public void beforeClass()
-      throws InterruptedException {
-    System.out.println(
-        "START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
+  public void beforeClass() throws InterruptedException {
+    System.out
+        .println("START " + getShortClassName() + " at " + new Date(System.currentTimeMillis()));
 
     // setup storage cluster
     _gSetupTool.addCluster(CLUSTER_NAME, true);
@@ -125,17 +124,14 @@ public class TestSemiAutoRebalance extends ZkTestBase {
   public void afterClass() throws Exception {
     _controller.syncStop();
     for (MockParticipantManager p : _participants) {
-      if (p.isConnected()) {
-        p.syncStop();
-      }
+      p.syncStop();
     }
     deleteCluster(CLUSTER_NAME);
     System.out.println("END " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
   }
 
   @Test
-  public void testAddParticipant()
-      throws InterruptedException {
+  public void testAddParticipant() throws InterruptedException {
     String newInstance = PARTICIPANT_PREFIX + "_" + (PARTICIPANT_START_PORT + _participants.size());
     _gSetupTool.addInstanceToCluster(CLUSTER_NAME, newInstance);
 
@@ -174,8 +170,7 @@ public class TestSemiAutoRebalance extends ZkTestBase {
   }
 
   @Test(dependsOnMethods = "testAddParticipant")
-  public void testStopAndReStartParticipant()
-      throws InterruptedException {
+  public void testStopAndReStartParticipant() throws InterruptedException {
     MockParticipantManager participant = _participants.get(0);
     String instance = participant.getInstanceName();
 
@@ -199,9 +194,8 @@ public class TestSemiAutoRebalance extends ZkTestBase {
     startParticipant(participant, affectedPartitions);
   }
 
-  private void stopParticipant(
-      MockParticipantManager participant, Map<String, MasterSlaveSMD.States> affectedPartitions)
-      throws InterruptedException {
+  private void stopParticipant(MockParticipantManager participant,
+      Map<String, MasterSlaveSMD.States> affectedPartitions) throws InterruptedException {
     participant.syncStop();
 
     Thread.sleep(1000);
@@ -215,9 +209,8 @@ public class TestSemiAutoRebalance extends ZkTestBase {
     }
   }
 
-  private void startParticipant(
-      MockParticipantManager participant, Map<String, MasterSlaveSMD.States> affectedPartitions)
-      throws InterruptedException {
+  private void startParticipant(MockParticipantManager participant,
+      Map<String, MasterSlaveSMD.States> affectedPartitions) throws InterruptedException {
     String instance = participant.getInstanceName();
     participant.syncStart();
 
diff --git a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestZeroReplicaAvoidance.java b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestZeroReplicaAvoidance.java
index 5283346..9ee4738 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestZeroReplicaAvoidance.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/rebalancer/TestZeroReplicaAvoidance.java
@@ -41,27 +41,29 @@ import org.apache.helix.model.StateModelDefinition;
 import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
 import org.apache.helix.tools.ClusterVerifiers.ZkHelixClusterVerifier;
 import org.testng.Assert;
+import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-public class TestZeroReplicaAvoidance extends ZkTestBase implements
-    ExternalViewChangeListener, IdealStateChangeListener{
-  final int NUM_NODE = 6;
-  final int START_PORT = 12918;
-  final String CLASS_NAME = getShortClassName();
-  final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
+public class TestZeroReplicaAvoidance extends ZkTestBase
+    implements ExternalViewChangeListener, IdealStateChangeListener {
+  private final int NUM_NODE = 6;
+  private final int START_PORT = 12918;
+  private final String CLASS_NAME = getShortClassName();
+  private final String CLUSTER_NAME = CLUSTER_PREFIX + "_" + CLASS_NAME;
 
-  List<MockParticipantManager> _participants = new ArrayList<MockParticipantManager>();
-  ZkHelixClusterVerifier _clusterVerifier;
-  boolean _testSuccess = true;
-  boolean _startListen = false;
+  private List<MockParticipantManager> _participants = new ArrayList<>();
+  private ZkHelixClusterVerifier _clusterVerifier;
+  private boolean _testSuccess = true;
+  private boolean _startListen = false;
+
+  private ClusterControllerManager _controller;
 
   @BeforeClass
   public void beforeClass() throws Exception {
     System.out.println("START " + CLASS_NAME + " at " + new Date(System.currentTimeMillis()));
 
     _gSetupTool.addCluster(CLUSTER_NAME, true);
-
     for (int i = 0; i < NUM_NODE; i++) {
       String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);
       _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName);
@@ -73,15 +75,27 @@ public class TestZeroReplicaAvoidance extends ZkTestBase implements
 
     // start controller
     String controllerName = CONTROLLER_PREFIX + "_0";
-    ClusterControllerManager controller =
-        new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
-    controller.syncStart();
+    _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName);
+    _controller.syncStart();
 
     _clusterVerifier =
         new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR).build();
   }
 
-  protected String[] TestStateModels = {
+  @AfterClass
+  public void afterClass() {
+    if (_controller != null && _controller.isConnected()) {
+      _controller.syncStop();
+    }
+    for (MockParticipantManager participant : _participants) {
+      if (participant != null && participant.isConnected()) {
+        participant.syncStop();
+      }
+    }
+    deleteCluster(CLUSTER_NAME);
+  }
+
+  private String[] TestStateModels = {
       BuiltInStateModelDefinitions.MasterSlave.name(),
       BuiltInStateModelDefinitions.OnlineOffline.name(),
       BuiltInStateModelDefinitions.LeaderStandby.name()
@@ -109,17 +123,21 @@ public class TestZeroReplicaAvoidance extends ZkTestBase implements
       createResourceWithDelayedRebalance(CLUSTER_NAME, db, stateModel, partition, replica, replica,
           0);
     }
-    Assert.assertTrue(_clusterVerifier.verify(50000));
+    Assert.assertTrue(_clusterVerifier.verify(50000L));
 
     _startListen = true;
-    DelayedTransition.setDelay(50);
+    DelayedTransition.setDelay(5);
 
     // add the other half of nodes.
     for (; i < NUM_NODE; i++) {
       _participants.get(i).syncStart();
     }
-    Assert.assertTrue(_clusterVerifier.verify(50000));
+    Assert.assertTrue(_clusterVerifier.verify(70000L));
     Assert.assertTrue(_testSuccess);
+
+    if (manager.isConnected()) {
+      manager.disconnect();
+    }
   }
 
   /**
@@ -148,8 +166,8 @@ public class TestZeroReplicaAvoidance extends ZkTestBase implements
     }
     if (instanceStateMap.size() < replica) {
       _testSuccess = false;
-      Assert.fail(String
-          .format("Resource %s partition %s has %d active replica, less than required %d!",
+      Assert.fail(
+          String.format("Resource %s partition %s has %d active replica, less than required %d!",
               resource, partition, instanceStateMap.size(), replica));
     }
 
@@ -164,9 +182,8 @@ public class TestZeroReplicaAvoidance extends ZkTestBase implements
       }
       if (topCount > 1) {
         _testSuccess = false;
-        Assert.fail(String
-            .format("Resource %s partition %s has %d replica in %s, more than 1!", resource,
-                partition, topCount, topState));
+        Assert.fail(String.format("Resource %s partition %s has %d replica in %s, more than 1!",
+            resource, partition, topCount, topState));
       }
     }
   }
@@ -178,14 +195,14 @@ public class TestZeroReplicaAvoidance extends ZkTestBase implements
       return;
     }
     for (ExternalView view : externalViewList) {
-      IdealState is = _gSetupTool.getClusterManagementTool()
-          .getResourceIdealState(CLUSTER_NAME, view.getResourceName());
+      IdealState is = _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME,
+          view.getResourceName());
       validateNoZeroReplica(is, view);
     }
   }
 
-  @Override public void onIdealStateChange(List<IdealState> idealStates,
-      NotificationContext changeContext) {
+  @Override
+  public void onIdealStateChange(List<IdealState> idealStates, NotificationContext changeContext) {
     if (!_startListen) {
       return;
     }
@@ -199,9 +216,10 @@ public class TestZeroReplicaAvoidance extends ZkTestBase implements
   private static class DelayedTransition extends MockTransition {
     private static long _delay = 0;
 
-    public static void setDelay (int delay) {
+    public static void setDelay(int delay) {
       _delay = delay;
     }
+
     @Override
     public void doTransition(Message message, NotificationContext context)
         throws InterruptedException {
diff --git a/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromCurrentStates.java b/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromCurrentStates.java
index a598a92..3e3b229 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromCurrentStates.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromCurrentStates.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration.spectator;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.lang.management.ManagementFactory;
 import java.util.HashSet;
 import java.util.List;
@@ -62,8 +81,8 @@ public class TestRoutingTableProviderFromCurrentStates extends ZkTestBase {
       _participants[i].syncStart();
     }
 
-    _manager = HelixManagerFactory
-        .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
+    _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin",
+        InstanceType.ADMINISTRATOR, ZK_ADDR);
     _manager.connect();
 
     String controllerName = CONTROLLER_PREFIX + "_0";
@@ -78,7 +97,7 @@ public class TestRoutingTableProviderFromCurrentStates extends ZkTestBase {
 
   @AfterClass
   public void afterClass() throws Exception {
-    /**
+    /*
      * shutdown order: 1) disconnect the controller 2) disconnect participants
      */
     if (_controller != null && _controller.isConnected()) {
@@ -92,7 +111,6 @@ public class TestRoutingTableProviderFromCurrentStates extends ZkTestBase {
     if (_manager != null && _manager.isConnected()) {
       _manager.disconnect();
     }
-
     deleteCluster(CLUSTER_NAME);
   }
 
@@ -100,19 +118,22 @@ public class TestRoutingTableProviderFromCurrentStates extends ZkTestBase {
   public void testRoutingTableWithCurrentStates() throws Exception {
     RoutingTableProvider routingTableEV =
         new RoutingTableProvider(_manager, PropertyType.EXTERNALVIEW);
-    RoutingTableProvider routingTableCurrentStates = new RoutingTableProvider(_manager, PropertyType.CURRENTSTATES);
+    RoutingTableProvider routingTableCurrentStates =
+        new RoutingTableProvider(_manager, PropertyType.CURRENTSTATES);
 
     try {
       String db1 = "TestDB-1";
-      _gSetupTool.addResourceToCluster(CLUSTER_NAME, db1, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name());
+      _gSetupTool.addResourceToCluster(CLUSTER_NAME, db1, NUM_PARTITIONS, "MasterSlave",
+          IdealState.RebalanceMode.FULL_AUTO.name());
       long startTime = System.currentTimeMillis();
       _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db1, NUM_REPLICAS);
 
-      Thread.sleep(200);
+      Thread.sleep(1000L);
       ZkHelixClusterVerifier clusterVerifier =
           new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR).build();
       Assert.assertTrue(clusterVerifier.verifyByPolling());
-      validatePropagationLatency(PropertyType.CURRENTSTATES, System.currentTimeMillis() - startTime);
+      validatePropagationLatency(PropertyType.CURRENTSTATES,
+          System.currentTimeMillis() - startTime);
 
       IdealState idealState1 =
           _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db1);
@@ -120,13 +141,15 @@ public class TestRoutingTableProviderFromCurrentStates extends ZkTestBase {
 
       // add new DB
       String db2 = "TestDB-2";
-      _gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name());
+      _gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, NUM_PARTITIONS, "MasterSlave",
+          IdealState.RebalanceMode.FULL_AUTO.name());
       startTime = System.currentTimeMillis();
       _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db2, NUM_REPLICAS);
 
-      Thread.sleep(200);
+      Thread.sleep(1000L);
       Assert.assertTrue(clusterVerifier.verifyByPolling());
-      validatePropagationLatency(PropertyType.CURRENTSTATES, System.currentTimeMillis() - startTime);
+      validatePropagationLatency(PropertyType.CURRENTSTATES,
+          System.currentTimeMillis() - startTime);
 
       IdealState idealState2 =
           _gSetupTool.getClusterManagementTool().getResourceIdealState(CLUSTER_NAME, db2);
@@ -135,9 +158,10 @@ public class TestRoutingTableProviderFromCurrentStates extends ZkTestBase {
       // shutdown an instance
       startTime = System.currentTimeMillis();
       _participants[0].syncStop();
-      Thread.sleep(200);
+      Thread.sleep(1000L);
       Assert.assertTrue(clusterVerifier.verifyByPolling());
-      validatePropagationLatency(PropertyType.CURRENTSTATES, System.currentTimeMillis() - startTime);
+      validatePropagationLatency(PropertyType.CURRENTSTATES,
+          System.currentTimeMillis() - startTime);
 
       validate(idealState1, routingTableEV, routingTableCurrentStates);
       validate(idealState2, routingTableEV, routingTableCurrentStates);
@@ -147,25 +171,24 @@ public class TestRoutingTableProviderFromCurrentStates extends ZkTestBase {
     }
   }
 
-  private ObjectName buildObjectName(PropertyType type)
-      throws MalformedObjectNameException {
+  private ObjectName buildObjectName(PropertyType type) throws MalformedObjectNameException {
     return MBeanRegistrar.buildObjectName(MonitorDomainNames.RoutingTableProvider.name(),
-        RoutingTableProviderMonitor.CLUSTER_KEY, CLUSTER_NAME, RoutingTableProviderMonitor.DATA_TYPE_KEY,
-        type.name());
+        RoutingTableProviderMonitor.CLUSTER_KEY, CLUSTER_NAME,
+        RoutingTableProviderMonitor.DATA_TYPE_KEY, type.name());
   }
 
   private void validatePropagationLatency(PropertyType type, final long upperBound)
       throws Exception {
     final ObjectName name = buildObjectName(type);
-    Assert.assertTrue(TestHelper.verify(new TestHelper.Verifier() {
-      @Override public boolean verify() throws Exception {
-        long stateLatency = (long) _beanServer.getAttribute(name, "StatePropagationLatencyGauge.Max");
-        return stateLatency > 0 && stateLatency <= upperBound;
-      }
+    Assert.assertTrue(TestHelper.verify(() -> {
+      long stateLatency = (long) _beanServer.getAttribute(name, "StatePropagationLatencyGauge.Max");
+      return stateLatency > 0 && stateLatency <= upperBound;
     }, 1000));
   }
 
-  @Test (dependsOnMethods = {"testRoutingTableWithCurrentStates"})
+  @Test(dependsOnMethods = {
+      "testRoutingTableWithCurrentStates"
+  })
   public void testWithSupportSourceDataType() {
     new RoutingTableProvider(_manager, PropertyType.EXTERNALVIEW).shutdown();
     new RoutingTableProvider(_manager, PropertyType.TARGETEXTERNALVIEW).shutdown();
diff --git a/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromTargetEV.java b/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromTargetEV.java
index 6a24986..50ccb36 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromTargetEV.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderFromTargetEV.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration.spectator;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
@@ -90,11 +109,10 @@ public class TestRoutingTableProviderFromTargetEV extends ZkTestBase {
     if (_manager != null && _manager.isConnected()) {
       _manager.disconnect();
     }
-
     deleteCluster(CLUSTER_NAME);
   }
 
-  @Test (expectedExceptions = HelixException.class)
+  @Test(expectedExceptions = HelixException.class)
   public void testTargetExternalViewWithoutEnable() {
     new RoutingTableProvider(_manager, PropertyType.TARGETEXTERNALVIEW);
   }
@@ -133,14 +151,11 @@ public class TestRoutingTableProviderFromTargetEV extends ZkTestBase {
       Assert.assertEquals(externalViewMasters.size(), 0);
 
       final Set<InstanceConfig> targetExternalViewMasters = new HashSet<>();
-      Assert.assertTrue(TestHelper.verify(new TestHelper.Verifier() {
-        @Override
-        public boolean verify() {
-          targetExternalViewMasters.clear();
-          targetExternalViewMasters.addAll(targetExternalViewProvider
-              .getInstancesForResource(WorkflowGenerator.DEFAULT_TGT_DB, "MASTER"));
-          return targetExternalViewMasters.size() == NUM_NODES;
-        }
+      Assert.assertTrue(TestHelper.verify(() -> {
+        targetExternalViewMasters.clear();
+        targetExternalViewMasters.addAll(targetExternalViewProvider
+            .getInstancesForResource(WorkflowGenerator.DEFAULT_TGT_DB, "MASTER"));
+        return targetExternalViewMasters.size() == NUM_NODES;
       }, 3000));
 
       // TargetExternalView MASTERS mapping should exactly match IdealState MASTERS mapping
@@ -160,7 +175,7 @@ public class TestRoutingTableProviderFromTargetEV extends ZkTestBase {
       for (InstanceConfig instanceConfig : targetExternalViewMasters) {
         targetMasters.add(instanceConfig.getInstanceName());
       }
-      Assert.assertTrue(idealMasters.equals(targetMasters));
+      Assert.assertEquals(targetMasters, idealMasters);
     } finally {
       externalViewProvider.shutdown();
       targetExternalViewProvider.shutdown();
diff --git a/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderPeriodicRefresh.java b/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderPeriodicRefresh.java
index e2b6df1..2aedfdc 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderPeriodicRefresh.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableProviderPeriodicRefresh.java
@@ -28,7 +28,8 @@ import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
 public class TestRoutingTableProviderPeriodicRefresh extends ZkTestBase {
-  private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TestRoutingTableProviderPeriodicRefresh.class);
+  private static final org.slf4j.Logger logger =
+      LoggerFactory.getLogger(TestRoutingTableProviderPeriodicRefresh.class);
 
   private static final String STATE_MODEL = BuiltInStateModelDefinitions.MasterSlave.name();
   private static final String TEST_DB = "TestDB";
diff --git a/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableSnapshot.java b/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableSnapshot.java
index 216c900..d4461a3 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableSnapshot.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/spectator/TestRoutingTableSnapshot.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration.spectator;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.List;
 import java.util.Set;
 import org.apache.helix.HelixManager;
@@ -20,7 +39,6 @@ import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-
 public class TestRoutingTableSnapshot extends ZkTestBase {
   private HelixManager _manager;
   private final int NUM_NODES = 10;
@@ -33,7 +51,7 @@ public class TestRoutingTableSnapshot extends ZkTestBase {
 
   @BeforeClass
   public void beforeClass() throws Exception {
-    _participants =  new MockParticipantManager[NUM_NODES];
+    _participants = new MockParticipantManager[NUM_NODES];
     _gSetupTool.addCluster(CLUSTER_NAME, true);
 
     _participants = new MockParticipantManager[NUM_NODES];
@@ -48,8 +66,8 @@ public class TestRoutingTableSnapshot extends ZkTestBase {
       _participants[i].syncStart();
     }
 
-    _manager = HelixManagerFactory
-        .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR);
+    _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin",
+        InstanceType.ADMINISTRATOR, ZK_ADDR);
     _manager.connect();
 
     String controllerName = CONTROLLER_PREFIX + "_0";
@@ -59,12 +77,18 @@ public class TestRoutingTableSnapshot extends ZkTestBase {
 
   @AfterClass
   public void afterClass() throws Exception {
-    _manager.disconnect();
+    if (_manager != null && _manager.isConnected()) {
+      _manager.disconnect();
+    }
     for (int i = 0; i < NUM_NODES; i++) {
       if (_participants[i] != null && _participants[i].isConnected()) {
         _participants[i].reset();
       }
     }
+    if (_controller != null && _controller.isConnected()) {
+      _controller.syncStop();
+    }
+    deleteCluster(CLUSTER_NAME);
   }
 
   @Test
@@ -74,7 +98,8 @@ public class TestRoutingTableSnapshot extends ZkTestBase {
 
     try {
       String db1 = "TestDB-1";
-      _gSetupTool.addResourceToCluster(CLUSTER_NAME, db1, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name());
+      _gSetupTool.addResourceToCluster(CLUSTER_NAME, db1, NUM_PARTITIONS, "MasterSlave",
+          IdealState.RebalanceMode.FULL_AUTO.name());
       _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db1, NUM_REPLICAS);
 
       Thread.sleep(200);
@@ -95,7 +120,8 @@ public class TestRoutingTableSnapshot extends ZkTestBase {
 
       // add new DB and shutdown an instance
       String db2 = "TestDB-2";
-      _gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, NUM_PARTITIONS, "MasterSlave", IdealState.RebalanceMode.FULL_AUTO.name());
+      _gSetupTool.addResourceToCluster(CLUSTER_NAME, db2, NUM_PARTITIONS, "MasterSlave",
+          IdealState.RebalanceMode.FULL_AUTO.name());
       _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, db2, NUM_REPLICAS);
 
       // shutdown an instance
@@ -133,4 +159,3 @@ public class TestRoutingTableSnapshot extends ZkTestBase {
     }
   }
 }
-
diff --git a/helix-core/src/test/java/org/apache/helix/integration/task/TestBatchAddJobs.java b/helix-core/src/test/java/org/apache/helix/integration/task/TestBatchAddJobs.java
index 36bbfa7..4645c42 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/task/TestBatchAddJobs.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/task/TestBatchAddJobs.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration.task;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
@@ -69,6 +88,8 @@ public class TestBatchAddJobs extends ZkTestBase {
     for (SubmitJobTask submitJobTask : _submitJobTasks) {
       submitJobTask.interrupt();
     }
+
+    deleteCluster(CLUSTER_NAME);
   }
 
   static class SubmitJobTask extends Thread {
@@ -76,8 +97,8 @@ public class TestBatchAddJobs extends ZkTestBase {
     private String _jobPrefixName;
 
     public SubmitJobTask(String zkAddress, int index) throws Exception {
-      HelixManager manager = HelixManagerFactory
-          .getZKHelixManager(CLUSTER_NAME, "Administrator", InstanceType.ADMINISTRATOR, zkAddress);
+      HelixManager manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Administrator",
+          InstanceType.ADMINISTRATOR, zkAddress);
       manager.connect();
       _driver = new TaskDriver(manager);
       _jobPrefixName = "JOB_" + index + "#";
diff --git a/helix-core/src/test/java/org/apache/helix/integration/task/TestDeleteWorkflow.java b/helix-core/src/test/java/org/apache/helix/integration/task/TestDeleteWorkflow.java
index 6a859e1..7e6aed1 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/task/TestDeleteWorkflow.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/task/TestDeleteWorkflow.java
@@ -1,5 +1,24 @@
 package org.apache.helix.integration.task;
 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
 import com.google.common.collect.ImmutableMap;
 import org.apache.helix.HelixAdmin;
 import org.apache.helix.HelixDataAccessor;
@@ -14,10 +33,9 @@ import org.testng.Assert;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
 
-
-public class TestDeleteWorkflow extends TaskTestBase  {
+public class TestDeleteWorkflow extends TaskTestBase {
   private static final int DELETE_DELAY = 2000;
-
+  private static final long FORCE_DELETE_BACKOFF = 200L;
   private HelixAdmin admin;
 
   @BeforeClass
@@ -31,17 +49,17 @@ public class TestDeleteWorkflow extends TaskTestBase  {
   public void testDeleteWorkflow() throws InterruptedException {
     String jobQueueName = TestHelper.getTestMethodName();
     JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG)
-        .setMaxAttemptsPerTask(1)
-        .setWorkflow(jobQueueName)
+        .setMaxAttemptsPerTask(1).setWorkflow(jobQueueName)
         .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "100000"));
 
     JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName);
     jobQueue.enqueueJob("job1", jobBuilder);
     _driver.start(jobQueue.build());
-    _driver.pollForJobState(jobQueueName,
-        TaskUtil.getNamespacedJobName(jobQueueName, "job1"), TaskState.IN_PROGRESS);
+    _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job1"),
+        TaskState.IN_PROGRESS);
 
-    // Check that WorkflowConfig, WorkflowContext, and IdealState are indeed created for this job queue
+    // Check that WorkflowConfig, WorkflowContext, and IdealState are indeed created for this job
+    // queue
     Assert.assertNotNull(_driver.getWorkflowConfig(jobQueueName));
     Assert.assertNotNull(_driver.getWorkflowContext(jobQueueName));
     Assert.assertNotNull(admin.getResourceIdealState(CLUSTER_NAME, jobQueueName));
@@ -52,7 +70,8 @@ public class TestDeleteWorkflow extends TaskTestBase  {
     // Attempt the deletion and time out
     try {
       _driver.deleteAndWaitForCompletion(jobQueueName, DELETE_DELAY);
-      Assert.fail("Delete must time out and throw a HelixException with the Controller paused, but did not!");
+      Assert.fail(
+          "Delete must time out and throw a HelixException with the Controller paused, but did not!");
     } catch (HelixException e) {
       // Pass
     }
@@ -71,8 +90,7 @@ public class TestDeleteWorkflow extends TaskTestBase  {
   public void testDeleteWorkflowForcefully() throws InterruptedException {
     String jobQueueName = TestHelper.getTestMethodName();
     JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG)
-        .setMaxAttemptsPerTask(1)
-        .setWorkflow(jobQueueName)
+        .setMaxAttemptsPerTask(1).setWorkflow(jobQueueName)
         .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000000"));
 
     JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName);
@@ -81,11 +99,13 @@ public class TestDeleteWorkflow extends TaskTestBase  {
     _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job1"),
         TaskState.IN_PROGRESS);
 
-    // Check that WorkflowConfig, WorkflowContext, and IdealState are indeed created for this job queue
+    // Check that WorkflowConfig, WorkflowContext, and IdealState are indeed created for this job
+    // queue
     Assert.assertNotNull(_driver.getWorkflowConfig(jobQueueName));
     Assert.assertNotNull(_driver.getWorkflowContext(jobQueueName));
     Assert.assertNotNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
-    Assert.assertNotNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
+    Assert
+        .assertNotNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
     Assert.assertNotNull(admin.getResourceIdealState(CLUSTER_NAME, jobQueueName));
 
     // Delete the idealstate of workflow
@@ -97,7 +117,8 @@ public class TestDeleteWorkflow extends TaskTestBase  {
     // Attempt the deletion and and it should time out since idealstate does not exist anymore.
     try {
       _driver.deleteAndWaitForCompletion(jobQueueName, DELETE_DELAY);
-      Assert.fail("Delete must time out and throw a HelixException with the Controller paused, but did not!");
+      Assert.fail(
+          "Delete must time out and throw a HelixException with the Controller paused, but did not!");
     } catch (HelixException e) {
       // Pass
     }
@@ -116,8 +137,7 @@ public class TestDeleteWorkflow extends TaskTestBase  {
   public void testDeleteHangingJobs() throws InterruptedException {
     String jobQueueName = TestHelper.getTestMethodName();
     JobConfig.Builder jobBuilder = JobConfig.Builder.fromMap(WorkflowGenerator.DEFAULT_JOB_CONFIG)
-        .setMaxAttemptsPerTask(1)
-        .setWorkflow(jobQueueName)
+        .setMaxAttemptsPerTask(1).setWorkflow(jobQueueName)
         .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "1000000"));
 
     JobQueue.Builder jobQueue = TaskTestUtil.buildJobQueue(jobQueueName);
@@ -126,11 +146,13 @@ public class TestDeleteWorkflow extends TaskTestBase  {
     _driver.pollForJobState(jobQueueName, TaskUtil.getNamespacedJobName(jobQueueName, "job1"),
         TaskState.IN_PROGRESS);
 
-    // Check that WorkflowConfig, WorkflowContext, and IdealState are indeed created for this job queue
+    // Check that WorkflowConfig, WorkflowContext, and IdealState are indeed created for this job
+    // queue
     Assert.assertNotNull(_driver.getWorkflowConfig(jobQueueName));
     Assert.assertNotNull(_driver.getWorkflowContext(jobQueueName));
     Assert.assertNotNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
-    Assert.assertNotNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
+    Assert
+        .assertNotNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
     Assert.assertNotNull(admin.getResourceIdealState(CLUSTER_NAME, jobQueueName));
 
     // Delete the idealstate, workflowconfig and context of workflow
@@ -153,7 +175,7 @@ public class TestDeleteWorkflow extends TaskTestBase  {
     Assert.assertNull(_driver.getWorkflowConfig(jobQueueName));
     Assert.assertNull(_driver.getWorkflowContext(jobQueueName));
 
-    // attemp to delete the job and it should fail with exception.
+    // Attempt to delete the job and it should fail with exception.
     try {
       _driver.deleteJob(jobQueueName, "job1");
       Assert.fail("Delete must be rejected and throw a HelixException, but did not!");
@@ -161,12 +183,20 @@ public class TestDeleteWorkflow extends TaskTestBase  {
       // Pass
     }
 
-    // delete forcefully
-    _driver.deleteJob(jobQueueName, "job1", true);
+    // delete forcefully a few times with a backoff (the controller may write back the ZNodes
+    // because force delete does not remove the job from the cache)
+    for (int i = 0; i < 3; i++) {
+      try {
+        _driver.deleteJob(jobQueueName, "job1", true);
+      } catch (Exception e) {
+        // Multiple delete calls are okay
+      }
+      Thread.sleep(FORCE_DELETE_BACKOFF);
+    }
 
     Assert.assertNull(_driver.getJobConfig(TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
     Assert.assertNull(_driver.getJobContext(TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
-    Assert.assertNull(admin
-        .getResourceIdealState(CLUSTER_NAME, TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
+    Assert.assertNull(admin.getResourceIdealState(CLUSTER_NAME,
+        TaskUtil.getNamespacedJobName(jobQueueName, "job1")));
   }
 }
\ No newline at end of file
diff --git a/helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailure.java b/helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailure.java
index 28d7f76..3447e4b 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailure.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/task/TestJobFailure.java
@@ -21,6 +21,7 @@ package org.apache.helix.integration.task;
 
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Sets;
+import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -63,15 +64,16 @@ public final class TestJobFailure extends TaskSynchronizedTestBase {
     _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, CONTROLLER_PREFIX);
     _controller.syncStart();
 
-    Thread.sleep(1000); // Wait for cluster to setup.
+    Thread.sleep(1000L); // Wait for cluster to setup.
   }
 
   private static final String EXPECTED_ENDING_STATE = "ExpectedEndingState";
   private static int testNum = 0;
 
   @Test(dataProvider = "testJobFailureInput")
-  public void testNormalJobFailure(String comment, List<String> taskStates, List<String> expectedTaskEndingStates,
-      String expectedJobEndingStates, String expectedWorkflowEndingStates) throws InterruptedException {
+  public void testNormalJobFailure(String comment, List<String> taskStates,
+      List<String> expectedTaskEndingStates, String expectedJobEndingStates,
+      String expectedWorkflowEndingStates) throws InterruptedException {
     final String JOB_NAME = "test_job";
     final String WORKFLOW_NAME = TestHelper.getTestMethodName() + testNum++;
     System.out.println("Test case comment: " + comment);
@@ -79,51 +81,56 @@ public final class TestJobFailure extends TaskSynchronizedTestBase {
     Map<String, Map<String, String>> targetPartitionConfigs =
         createPartitionConfig(taskStates, expectedTaskEndingStates);
 
-    JobConfig.Builder firstJobBuilder = new JobConfig.Builder()
-        .setWorkflow(WORKFLOW_NAME)
-        .setTargetResource(DB_NAME)
-        .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name()))
-        .setCommand(MockTask.TASK_COMMAND)
-        .setJobCommandConfigMap(ImmutableMap.of(
-            MockTask.TARGET_PARTITION_CONFIG, MockTask.serializeTargetPartitionConfig(targetPartitionConfigs)));
+    JobConfig.Builder firstJobBuilder =
+        new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME)
+            .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name()))
+            .setCommand(MockTask.TASK_COMMAND)
+            .setJobCommandConfigMap(ImmutableMap.of(MockTask.TARGET_PARTITION_CONFIG,
+                MockTask.serializeTargetPartitionConfig(targetPartitionConfigs)));
 
-    Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW_NAME)
-        .addJob(JOB_NAME, firstJobBuilder);
+    Workflow.Builder workflowBuilder =
+        new Workflow.Builder(WORKFLOW_NAME).addJob(JOB_NAME, firstJobBuilder);
 
     _driver.start(workflowBuilder.build());
-
     _driver.pollForJobState(WORKFLOW_NAME, TaskUtil.getNamespacedJobName(WORKFLOW_NAME, JOB_NAME),
         TaskState.valueOf(expectedJobEndingStates));
     _driver.pollForWorkflowState(WORKFLOW_NAME, TaskState.valueOf(expectedWorkflowEndingStates));
 
-    Thread.sleep(2000);
-    JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW_NAME, JOB_NAME));
+    JobContext jobContext =
+        _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW_NAME, JOB_NAME));
     for (int pId : jobContext.getPartitionSet()) {
-      Map<String, String> targetPartitionConfig = targetPartitionConfigs.get(jobContext.getTargetForPartition(pId));
-      Assert.assertEquals(jobContext.getPartitionState(pId).name(), targetPartitionConfig.get(EXPECTED_ENDING_STATE));
+      Map<String, String> targetPartitionConfig =
+          targetPartitionConfigs.get(jobContext.getTargetForPartition(pId));
+      Assert
+          .assertTrue(Arrays.asList(targetPartitionConfig.get(EXPECTED_ENDING_STATE).split("\\s+"))
+              .contains(jobContext.getPartitionState(pId).name()));
     }
   }
 
   @DataProvider(name = "testJobFailureInput")
   public Object[][] loadtestJobFailureInput() {
-    String[] params = {"comment", "taskStates", "expectedTaskEndingStates", "expectedJobEndingStates",
-        "expectedWorkflowEndingStates"};
+    String[] params = {
+        "comment", "taskStates", "expectedTaskEndingStates", "expectedJobEndingStates",
+        "expectedWorkflowEndingStates"
+    };
     return TestInputLoader.loadTestInputs("TestJobFailure.json", params);
   }
 
   private Map<String, Map<String, String>> createPartitionConfig(List<String> taskStates,
       List<String> expectedTaskEndingStates) {
-    Map<String, Map<String, String>> targetPartitionConfigs = new HashMap<String, Map<String, String>>();
-    ExternalView externalView = _manager.getClusterManagmentTool().getResourceExternalView(CLUSTER_NAME, DB_NAME);
+    Map<String, Map<String, String>> targetPartitionConfigs = new HashMap<>();
+    ExternalView externalView =
+        _manager.getClusterManagmentTool().getResourceExternalView(CLUSTER_NAME, DB_NAME);
     Set<String> partitionSet = externalView.getPartitionSet();
     if (taskStates.size() != partitionSet.size()) {
       throw new IllegalArgumentException(
           "Input size does not match number of partitions for target resource: " + DB_NAME);
     }
     int i = 0;
-    // Set job command configs for target partitions(order doesn't matter) according to specified task states.
+    // Set job command configs for target partitions(order doesn't matter) according to specified
+    // task states.
     for (String partition : partitionSet) {
-      Map<String, String> config = new HashMap<String, String>();
+      Map<String, String> config = new HashMap<>();
       if (taskStates.get(i).equals(TaskPartitionState.COMPLETED.name())) {
         config.put(MockTask.TASK_RESULT_STATUS, TaskResult.Status.COMPLETED.name());
       } else if (taskStates.get(i).equals(TaskPartitionState.TASK_ERROR.name())) {
diff --git a/helix-core/src/test/java/org/apache/helix/integration/task/TestJobTimeout.java b/helix-core/src/test/java/org/apache/helix/integration/task/TestJobTimeout.java
index 8da4c92..9b171ff 100644
--- a/helix-core/src/test/java/org/apache/helix/integration/task/TestJobTimeout.java
+++ b/helix-core/src/test/java/org/apache/helix/integration/task/TestJobTimeout.java
@@ -21,9 +21,11 @@ package org.apache.helix.integration.task;
 
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Sets;
+import java.util.Map;
 import org.apache.helix.TestHelper;
 import org.apache.helix.integration.manager.ClusterControllerManager;
 import org.apache.helix.integration.manager.MockParticipantManager;
+import org.apache.helix.model.ExternalView;
 import org.apache.helix.model.MasterSlaveSMD;
 import org.apache.helix.task.JobConfig;
 import org.apache.helix.task.JobContext;
@@ -33,6 +35,7 @@ import org.apache.helix.task.TaskSynchronizedTestBase;
 import org.apache.helix.task.TaskUtil;
 import org.apache.helix.task.Workflow;
 import org.apache.helix.task.WorkflowConfig;
+import org.apache.helix.tools.ClusterVerifiers.BestPossibleExternalViewVerifier;
 import org.testng.Assert;
 import org.testng.annotations.BeforeClass;
 import org.testng.annotations.Test;
@@ -45,7 +48,7 @@ public final class TestJobTimeout extends TaskSynchronizedTestBase {
     _numPartitions = 2;
     _numReplicas = 1; // only Master, no Slave
     _numDbs = 1;
-    _participants =  new MockParticipantManager[_numNodes];
+    _participants = new MockParticipantManager[_numNodes];
 
     _gSetupTool.addCluster(CLUSTER_NAME, true);
     setupParticipants();
@@ -58,36 +61,35 @@ public final class TestJobTimeout extends TaskSynchronizedTestBase {
 
   @Test
   public void testTaskRunningIndefinitely() throws InterruptedException {
-    // first job runs indefinitely and timeout, the second job runs successfully, the workflow succeed.
+    // first job runs indefinitely and timeout, the second job runs successfully, the workflow
+    // succeed.
     final String FIRST_JOB = "first_job";
     final String SECOND_JOB = "second_job";
     final String WORKFLOW_NAME = TestHelper.getTestMethodName();
     final String DB_NAME = WorkflowGenerator.DEFAULT_TGT_DB;
 
-    JobConfig.Builder firstJobBuilder = new JobConfig.Builder()
-        .setWorkflow(WORKFLOW_NAME)
-        .setTargetResource(DB_NAME)
-        .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name()))
-        .setCommand(MockTask.TASK_COMMAND)
-        .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")) // task stuck
-        .setTimeout(1000);
-
-    JobConfig.Builder secondJobBuilder = new JobConfig.Builder()
-        .setWorkflow(WORKFLOW_NAME)
-        .setTargetResource(DB_NAME)
-        .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name()))
-        .setCommand(MockTask.TASK_COMMAND)
-        .setIgnoreDependentJobFailure(true); // ignore first job's timeout
-
-    WorkflowConfig.Builder workflowConfigBuilder = new WorkflowConfig.Builder(WORKFLOW_NAME)
-        .setFailureThreshold(
-            1); // workflow ignores first job's timeout and schedule second job and succeed.
+    JobConfig.Builder firstJobBuilder =
+        new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME)
+            .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name()))
+            .setCommand(MockTask.TASK_COMMAND)
+            .setJobCommandConfigMap(ImmutableMap.of(MockTask.JOB_DELAY, "99999999")) // task stuck
+            .setTimeout(10);
+
+    JobConfig.Builder secondJobBuilder =
+        new JobConfig.Builder().setWorkflow(WORKFLOW_NAME).setTargetResource(DB_NAME)
+            .setTargetPartitionStates(Sets.newHashSet(MasterSlaveSMD.States.MASTER.name()))
+            .setCommand(MockTask.TASK_COMMAND).setIgnoreDependentJobFailure(true); // ignore first
+                                                                                   // job's timeout
+
+    WorkflowConfig.Builder workflowConfigBuilder =
+        new WorkflowConfig.Builder(WORKFLOW_NAME).setFailureThreshold(1); // workflow ignores first
+                                                                          // job's timeout and
+                                                                          // schedule second job and
+                                                                          // succeed.
 
     Workflow.Builder workflowBuilder = new Workflow.Builder(WORKFLOW_NAME)
-        .setWorkflowConfig(workflowConfigBuilder.build())
-        .addJob(FIRST_JOB, firstJobBuilder)
-        .addJob(SECOND_JOB, secondJobBuilder)
-        .addParentChildDependency(FIRST_JOB, SECOND_JOB);
+        .setWorkflowConfig(workflowConfigBuilder.build()).addJob(FIRST_JOB, firstJobBuilder)
+        .addJob(SECOND_JOB, secondJobBuilder).addParentChildDependency(FIRST_JOB, SECOND_JOB);
 
     _driver.start(workflowBuilder.build());
 
@@ -97,7 +99,8 @@ public final class TestJobTimeout extends TaskSynchronizedTestBase {
         TaskState.COMPLETED);
     _driver.pollForWorkflowState(WORKFLOW_NAME, TaskState.COMPLETED);
 
-    JobContext jobContext = _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW_NAME, FIRST_JOB));
+    JobContext jobContext =
+        _driver.getJobContext(TaskUtil.getNamespacedJobName(WORKFLOW_NAME, FIRST_JOB));
     for (int pId : jobContext.getPartitionSet()) {
... 4550 lines suppressed ...


Mime
View raw message