1 package delight.nashornsandbox.internal; 2 3 import java.lang.management.ManagementFactory; 4 import java.lang.management.ThreadMXBean; 5 import java.util.concurrent.atomic.AtomicBoolean; 6 import org.eclipse.xtext.xbase.lib.Exceptions; 7 import org.eclipse.xtext.xbase.lib.InputOutput; 8 9 @SuppressWarnings("all") 10 public class MonitorThread extends Thread { 11 private final long maxCPUTime; 12 13 private final AtomicBoolean stop; 14 15 private final AtomicBoolean operationInterrupted; 16 17 private Thread threadToMonitor; 18 19 private Runnable onInvalid; 20 21 private final AtomicBoolean cpuLimitExceeded; 22 23 @Override 24 public void run() { 25 try { 26 final ThreadMXBean bean = ManagementFactory.getThreadMXBean(); 27 long _id = this.threadToMonitor.getId(); 28 final long startCPUTime = bean.getThreadCpuTime(_id); 29 while ((!this.stop.get())) { 30 { 31 long _id_1 = this.threadToMonitor.getId(); 32 final long threadCPUTime = bean.getThreadCpuTime(_id_1); 33 final long runtime = (threadCPUTime - startCPUTime); 34 if ((runtime > this.maxCPUTime)) { 35 this.cpuLimitExceeded.set(true); 36 this.stop.set(true); 37 this.onInvalid.run(); 38 Thread.sleep(50); 39 boolean _get = this.operationInterrupted.get(); 40 boolean _equals = (_get == false); 41 if (_equals) { 42 String _plus = (this + ": Thread hard shutdown!"); 43 InputOutput.<String>println(_plus); 44 this.threadToMonitor.stop(); 45 } 46 return; 47 } 48 Thread.sleep(5); 49 } 50 } 51 } catch (Throwable _e) { 52 throw Exceptions.sneakyThrow(_e); 53 } 54 } 55 56 public void stopMonitor() { 57 this.stop.set(true); 58 } 59 60 public void setThreadToMonitor(final Thread t) { 61 this.threadToMonitor = t; 62 } 63 64 public void setOnInvalidHandler(final Runnable r) { 65 this.onInvalid = r; 66 } 67 68 public void notifyOperationInterrupted() { 69 this.operationInterrupted.set(true); 70 } 71 72 public boolean isCPULimitExceeded() { 73 return this.cpuLimitExceeded.get(); 74 } 75 76 public boolean gracefullyInterrputed() { 77 return this.operationInterrupted.get(); 78 } 79 80 public MonitorThread(final long maxCPUTimne) { 81 this.maxCPUTime = maxCPUTimne; 82 AtomicBoolean _atomicBoolean = new AtomicBoolean(false); 83 this.stop = _atomicBoolean; 84 AtomicBoolean _atomicBoolean_1 = new AtomicBoolean(false); 85 this.operationInterrupted = _atomicBoolean_1; 86 AtomicBoolean _atomicBoolean_2 = new AtomicBoolean(false); 87 this.cpuLimitExceeded = _atomicBoolean_2; 88 } 89 }