/*
 * Copyright 2011,2012 Metamarkets Group Inc.
 *
 * Licensed 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.
 */

package com.metamx.common.concurrent;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.metamx.common.lifecycle.Lifecycle;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServices
{
  public static ExecutorService create(Lifecycle lifecycle, ExecutorServiceConfig config)
  {
    return manageLifecycle(
        lifecycle,
        Executors.newFixedThreadPool(
            config.getNumThreads(),
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat(config.getFormatString()).build()
        )
    );
  }

  public static <T extends ExecutorService> T manageLifecycle(Lifecycle lifecycle, final T service)
  {
    lifecycle.addHandler(
        new Lifecycle.Handler()
        {
          @Override
          public void start() throws Exception
          {
          }

          @Override
          public void stop()
          {
            service.shutdownNow();
          }
        }
    );

    return service;
  }
}

@@ -644,16 +644,58 @@
 rrent;%0A%0A
+import com.google.common.base.Throwables;%0A
 import c
@@ -1353,24 +1353,36 @@
 ervice)%0A  %7B%0A
+    try %7B%0A  
     lifecycl
@@ -1386,16 +1386,26 @@
 ycle.add
+MaybeStart
 Handler(
@@ -1409,24 +1409,26 @@
 er(%0A        
+  
 new Lifecycl
@@ -1439,34 +1439,38 @@
 ndler()%0A        
-%7B%0A
+  %7B%0A  
           @Overr
@@ -1475,32 +1475,34 @@
 rride%0A          
+ 
+ 
 public void star
@@ -1524,34 +1524,38 @@
 ption%0A          
-%7B%0A
+  %7B%0A  
           %7D%0A%0A   
@@ -1553,32 +1553,34 @@
    %7D%0A%0A          
+  
 @Override%0A      
@@ -1575,32 +1575,34 @@
 rride%0A          
+ 
+ 
 public void stop
@@ -1606,32 +1606,34 @@
 top()%0A          
+  
 %7B%0A            se
@@ -1630,16 +1630,18 @@
         
+ 
+ 
 service.
@@ -1655,16 +1655,18 @@
 nNow();%0A
+  
         
@@ -1681,17 +1681,89 @@
     
-%7D%0A
+  %7D%0A  
     );%0A
+    %7D%0A    catch (Exception e) %7B%0A      Throwables.propagate(e);%0A    %7D
 %0A   

Add and maybe start handler instead of add. Exception will be raise if the service did started