View Javadoc

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        final long startCPUTime = bean.getThreadCpuTime(this.threadToMonitor.getId());
28        while ((!this.stop.get())) {
29          {
30            final long threadCPUTime = bean.getThreadCpuTime(this.threadToMonitor.getId());
31            final long runtime = (threadCPUTime - startCPUTime);
32            if ((runtime > this.maxCPUTime)) {
33              this.cpuLimitExceeded.set(true);
34              this.stop.set(true);
35              this.onInvalid.run();
36              Thread.sleep(50);
37              boolean _get = this.operationInterrupted.get();
38              boolean _equals = (_get == false);
39              if (_equals) {
40                String _plus = (this + ": Thread hard shutdown!");
41                InputOutput.<String>println(_plus);
42                this.threadToMonitor.stop();
43              }
44              return;
45            }
46            Thread.sleep(5);
47          }
48        }
49      } catch (Throwable _e) {
50        throw Exceptions.sneakyThrow(_e);
51      }
52    }
53    
54    public void stopMonitor() {
55      this.stop.set(true);
56    }
57    
58    public void setThreadToMonitor(final Thread t) {
59      this.threadToMonitor = t;
60    }
61    
62    public void setOnInvalidHandler(final Runnable r) {
63      this.onInvalid = r;
64    }
65    
66    public void notifyOperationInterrupted() {
67      this.operationInterrupted.set(true);
68    }
69    
70    public boolean isCPULimitExceeded() {
71      return this.cpuLimitExceeded.get();
72    }
73    
74    public boolean gracefullyInterrputed() {
75      return this.operationInterrupted.get();
76    }
77    
78    public MonitorThread(final long maxCPUTimne) {
79      this.maxCPUTime = maxCPUTimne;
80      AtomicBoolean _atomicBoolean = new AtomicBoolean(false);
81      this.stop = _atomicBoolean;
82      AtomicBoolean _atomicBoolean_1 = new AtomicBoolean(false);
83      this.operationInterrupted = _atomicBoolean_1;
84      AtomicBoolean _atomicBoolean_2 = new AtomicBoolean(false);
85      this.cpuLimitExceeded = _atomicBoolean_2;
86    }
87  }