Cleaning-up shared executors use of metrics service.

Change-Id: I4293df87cd46e9f22cbdf03cfbced9a21ba85de7
diff --git a/core/net/src/main/java/org/onosproject/core/impl/CoreManager.java b/core/net/src/main/java/org/onosproject/core/impl/CoreManager.java
index a8405dd..2b44b2a 100644
--- a/core/net/src/main/java/org/onosproject/core/impl/CoreManager.java
+++ b/core/net/src/main/java/org/onosproject/core/impl/CoreManager.java
@@ -101,7 +101,7 @@
 
 
     @Activate
-    public void activate() {
+    protected void activate() {
         registerApplication(CORE_APP_NAME);
         cfgService.registerProperties(getClass());
         try {
@@ -117,7 +117,7 @@
     }
 
     @Deactivate
-    public void deactivate() {
+    protected void deactivate() {
         cfgService.unregisterProperties(getClass(), false);
         SharedExecutors.shutdown();
     }
@@ -171,7 +171,7 @@
 
 
     @Modified
-    public void modified(ComponentContext context) {
+    protected void modified(ComponentContext context) {
         Dictionary<?, ?> properties = context.getProperties();
         Integer poolSize = Tools.getIntegerProperty(properties, "sharedThreadPoolSize");
 
@@ -193,7 +193,7 @@
         Boolean performanceCheck = Tools.isPropertyEnabled(properties, "sharedThreadPerformanceCheck");
         if (performanceCheck != null) {
             calculatePoolPerformance = performanceCheck;
-            SharedExecutors.setCalculatePoolPerformance(calculatePoolPerformance, metricsService);
+            SharedExecutors.setMetricsService(calculatePoolPerformance ? metricsService : null);
         }
 
         log.info("Settings: sharedThreadPoolSize={}, maxEventTimeLimit={}, calculatePoolPerformance={}",
diff --git a/utils/misc/src/main/java/org/onlab/util/SharedExecutorService.java b/utils/misc/src/main/java/org/onlab/util/SharedExecutorService.java
index 1963b17..e4e0bc2 100644
--- a/utils/misc/src/main/java/org/onlab/util/SharedExecutorService.java
+++ b/utils/misc/src/main/java/org/onlab/util/SharedExecutorService.java
@@ -112,30 +112,29 @@
         Counter taskCounter = new Counter();
         taskCounter.reset();
         return executor.submit(() -> {
-                    T t = null;
-                    long queueWaitTime = (long) taskCounter.duration();
-                    Class className;
-                    if (task instanceof  CallableExtended) {
-                        className =  ((CallableExtended) task).getRunnable().getClass();
-                    } else {
-                        className = task.getClass();
-                    }
-                    if (queueMetrics != null) {
-                        queueMetrics.update(queueWaitTime, TimeUnit.SECONDS);
-                    }
-                    taskCounter.reset();
-                    try {
-                        t = task.call();
-                    } catch (Exception e) {
-                        getLogger(className).error("Uncaught exception on " + className, e);
-                    }
-                    long taskwaittime = (long) taskCounter.duration();
-                    if (delayMetrics != null) {
-                        delayMetrics.update(taskwaittime, TimeUnit.SECONDS);
-                    }
-                    return t;
-                }
-        );
+                   T t = null;
+                   long queueWaitTime = (long) taskCounter.duration();
+                   Class className;
+                   if (task instanceof CallableExtended) {
+                       className = ((CallableExtended) task).getRunnable().getClass();
+                   } else {
+                       className = task.getClass();
+                   }
+                   if (queueMetrics != null) {
+                       queueMetrics.update(queueWaitTime, TimeUnit.SECONDS);
+                   }
+                   taskCounter.reset();
+                   try {
+                       t = task.call();
+                   } catch (Exception e) {
+                       getLogger(className).error("Uncaught exception on " + className, e);
+                   }
+                   long taskwaittime = (long) taskCounter.duration();
+                   if (delayMetrics != null) {
+                       delayMetrics.update(taskwaittime, TimeUnit.SECONDS);
+                   }
+                   return t;
+               });
     }
 
     @Override
@@ -179,20 +178,26 @@
         executor.execute(command);
     }
 
-    public void setCalculatePoolPerformance(boolean calculatePoolPerformance, MetricsService metricsSrv) {
-       this.metricsService = metricsSrv;
-       if (calculatePoolPerformance) {
-           if (metricsService != null) {
-               executorMetrics = metricsService.registerComponent("SharedExecutor");
-               MetricsFeature mf = executorMetrics.registerFeature("*");
-               queueMetrics = metricsService.createTimer(executorMetrics, mf, "Queue");
-               delayMetrics = metricsService.createTimer(executorMetrics, mf, "Delay");
-           }
-       } else {
-           metricsService = null;
-           queueMetrics = null;
-           delayMetrics = null;
-       }
+    /**
+     * Enables or disables calculation of the pool performance metrics. If
+     * the metrics service is not null metric collection will be enabled;
+     * otherwise it will be disabled.
+     *
+     * @param metricsService optional metric service
+     */
+    public void setMetricsService(MetricsService metricsService) {
+        if (this.metricsService == null && metricsService != null) {
+            // If metrics service was newly introduced, initialize metrics.
+            executorMetrics = metricsService.registerComponent("SharedExecutor");
+            MetricsFeature mf = executorMetrics.registerFeature("*");
+            queueMetrics = metricsService.createTimer(executorMetrics, mf, "Queue");
+            delayMetrics = metricsService.createTimer(executorMetrics, mf, "Delay");
+        } else if (this.metricsService != null && metricsService == null) {
+            // If the metrics service was newly withdrawn, tear-down metrics.
+            queueMetrics = null;
+            delayMetrics = null;
+        } // Otherwise just record the metrics service
+        this.metricsService = metricsService;
     }
 
     private Runnable wrap(Runnable command) {
@@ -223,8 +228,8 @@
     }
 
     /**
-     *  CallableExtended class is used to get Runnable Object
-     *  from Callable Object.
+     * CallableExtended class is used to get Runnable Object
+     * from Callable Object.
      */
     class CallableExtended implements Callable {
 
@@ -232,11 +237,13 @@
 
         /**
          * Wrapper for Callable object .
+         *
          * @param runnable Runnable object
          */
         public CallableExtended(Runnable runnable) {
             this.runnable = runnable;
         }
+
         public Runnable getRunnable() {
             return runnable;
         }
diff --git a/utils/misc/src/main/java/org/onlab/util/SharedExecutors.java b/utils/misc/src/main/java/org/onlab/util/SharedExecutors.java
index d0e7ff1..e4f5e5b 100644
--- a/utils/misc/src/main/java/org/onlab/util/SharedExecutors.java
+++ b/utils/misc/src/main/java/org/onlab/util/SharedExecutors.java
@@ -95,9 +95,15 @@
                                                             "onos-pool-executor-%d")));
     }
 
-
-    public static void setCalculatePoolPerformance(boolean calculatePoolPerformance, MetricsService metricsService) {
-        poolThreadExecutor.setCalculatePoolPerformance(calculatePoolPerformance, metricsService);
+    /**
+     * Enables or disables calculation of the pool performance metrics. If
+     * the metrics service is not null metric collection will be enabled;
+     * otherwise it will be disabled.
+     *
+     * @param metricsService optional metric service
+     */
+    public static void setMetricsService(MetricsService metricsService) {
+        poolThreadExecutor.setMetricsService(metricsService);
     }
 
     /**