/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.twosigma.beaker.jvm.threads;

import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class BeakerCellExecutor {

  private final String prefix;
  private final ReentrantLock theLock;
  private BeakerSingleThreadFactory thrFactory;
  private ThreadGroup thrGroup;
  private ExecutorService worker;
  private static AtomicInteger count = new AtomicInteger();
  
  public BeakerCellExecutor(String prf) {
    prefix   = prf;
    theLock  = new ReentrantLock();
    thrGroup = new ThreadGroup(prefix + "TG" + count.getAndIncrement());
    reset();
  }
  
  public void reset() {
    theLock.lock();
    thrFactory = new BeakerSingleThreadFactory(thrGroup, prefix);
    worker = Executors.newSingleThreadExecutor(thrFactory);
    theLock.unlock();
  }
  
  public boolean executeTask(Runnable tsk) {
    Future<?> ret;
    
    try {
      theLock.lock();
      ret = worker.submit(tsk);
    } catch(Throwable t) {
      t.printStackTrace();
      return false;
    } finally {
      theLock.unlock();
    }

    try {
      ret.get();
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    if(ret.isCancelled())
      return false;
    return true;
  }
  
 
  @SuppressWarnings("deprecation")
  public void cancelExecution() {
    // stop current execution (if any)
    theLock.lock();
    worker.shutdownNow();
    Thread thr = thrFactory.getTheThread();
    if (thr != null) {
      int repeat = 5;
      while(repeat>0 && !thr.getState().equals(State.TERMINATED)) {
        repeat--;
        try {  Thread.sleep(100);  } catch (Throwable t) { }
      }
      if(!thr.getState().equals(State.TERMINATED)) {
        repeat = 15;
        while(repeat>0 && !thr.getState().equals(State.TERMINATED)) {
          repeat--;
          thr.stop();
          try {  Thread.sleep(100);  } catch (Throwable t) { }
        }
      }
    }
    theLock.unlock();
    
    // reset executor service
    reset();
  }
  
  public List<Thread> getThreadList() { 
    int nAlloc = thrGroup.activeCount( );
    if (nAlloc == 0)
      return new ArrayList<Thread>();
    int n = 0;
    Thread[] threads;
    do {
        nAlloc *= 2;
        threads = new Thread[ nAlloc ];
        n = thrGroup.enumerate( threads );
    } while ( n == nAlloc );
    return Arrays.asList(threads);
  }
  
  @SuppressWarnings("deprecation")
  public void killAllThreads() {
    // first stop current execution (if any)
    theLock.lock();
    worker.shutdownNow();
    Thread thr = thrFactory.getTheThread();
    int repeat;
    if(thr != null) {
      repeat = 5;
      while(repeat>0 && !thr.getState().equals(State.TERMINATED)) {
        repeat--;
        try {  Thread.sleep(100);  } catch (Throwable t) { }
      }
      if(!thr.getState().equals(State.TERMINATED)) {
        repeat = 15;
        while(repeat>0 && !thr.getState().equals(State.TERMINATED)) {
          repeat--;
          thr.stop();
          try {  Thread.sleep(100);  } catch (Throwable t) { }
        }
      }
    }
    
    // then kill all remaining threads in the threadpool
    List<Thread> tlist = getThreadList();
    
    for (Thread t : tlist) {
      if (t!=null)
        t.interrupt();
    }

    repeat = 15;
    while(repeat>0) {
      boolean finished = true;
      for (Thread t : tlist) {
        if (t!=null && ! t.getState().equals(State.TERMINATED) ) {
          finished = false;
          t.stop();
        }
      }
      if (finished)
        break;
      repeat--;
      try {  Thread.sleep(100);  } catch (Throwable t) { }
    }

    theLock.unlock();

    // reset executor service
    reset();
  }
  
  
}

@@ -988,42 +988,201 @@
 ck;%0A
-%0Apublic class BeakerCellExecutor %7B
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0A%0Apublic class BeakerCellExecutor %7B%0A%0A  private static final Logger logger = LoggerFactory.getLogger(BeakerCellExecutor.class.getName());
 %0A%0A  
@@ -2330,41 +2330,58 @@
   //
- stop current execution (if any)%0A
+logger.info(%22cancelExecution begin%22);%0A    try %7B%0A  
     
@@ -2392,32 +2392,34 @@
 ock.lock();%0A    
+  
 worker.shutdownN
@@ -2416,32 +2416,34 @@
 .shutdownNow();%0A
+  
     Thread thr =
@@ -2466,24 +2466,26 @@
 heThread();%0A
+  
     if (thr 
@@ -2505,109 +2505,79 @@
     
-int repeat = 5;%0A      while(repeat%3E0 && !thr.getState().equals(State.TERMINATED)) %7B%0A        repeat--;
+  //logger.info(%22interrupting%22);%0A        thr.interrupt();%0A        try %7B
 %0A   
@@ -2573,37 +2573,32 @@
   try %7B%0A        
-try %7B
   Thread.sleep(1
@@ -2600,300 +2600,194 @@
 eep(
-1
+20
 00);
-  %7D catch (Throwable t) %7B %7D%0A      %7D%0A      if(!thr.getState().equals(State.TERMINATED)) %7B%0A        repeat = 15;%0A        while(repeat%3E0 && !thr.getState().equals(State.TERMINATED)) %7B%0A          repeat--;%0A          thr.stop();%0A          try %7B  Thread.sleep(100
+%0A        %7D catch (InterruptedException ex) %7B%0A        %7D%0A        if (!thr.getState().equals(State.TERMINATED)) %7B%0A          //logger.info(%22stopping%22);%0A          thr.stop(
 );
+%0A
   
-%7D catch (Throwable t) %7B
+     
  %7D%0A
-  
     
@@ -2790,34 +2790,38 @@
       %7D%0A    
-  %7D%0A    %7D%0A
+%7D finally %7B%0A  
     theLock.
@@ -2838,51 +2838,69 @@
     
-%0A    // reset executor service%0A    reset();
+  reset();%0A      //logger.info(%22cancelExecution done%22);%0A    %7D
 %0A  %7D

rewrite jvm canceller to avoid looping and to interrupt first