View Javadoc

1   package de.mxro.service.internal;
2   
3   import de.mxro.concurrency.Concurrency;
4   import de.mxro.concurrency.wrappers.SimpleAtomicBoolean;
5   import de.mxro.concurrency.wrappers.SimpleAtomicInteger;
6   import de.mxro.service.utils.OperationCounter;
7   import de.mxro.service.utils.ShutdownHelper;
8   import delight.async.callbacks.SimpleCallback;
9   
10  public class ShutdownHelperImpl implements ShutdownHelper {
11  
12      private final OperationCounter operationCounter;
13  
14      private final SimpleAtomicInteger shutdownAttempts;
15      private final SimpleAtomicBoolean isShutdown;
16      private final SimpleAtomicBoolean isShuttingDown;
17      private final Concurrency con;
18  
19      private final static int DEFAULT_DELAY = 10;
20      private final static int MAX_ATTEMPTS = 300;
21  
22      @Override
23      public boolean isShutdown() {
24          return isShutdown.get();
25      }
26  
27      @Override
28      public boolean isShuttingDown() {
29          return isShuttingDown.get();
30      }
31  
32      @Override
33      public void shutdown(final SimpleCallback callback) {
34          assert !this.isShutdown() : "Cannot shut down already shut down server.";
35          assert !this.isShuttingDown() : "Cannot shut down server which is already shutting down.";
36  
37          this.isShuttingDown.set(true);
38  
39          if (operationCounter.count() == 0) {
40              this.isShutdown.set(true);
41              callback.onSuccess();
42  
43              return;
44          }
45  
46          con.newTimer().scheduleOnce(DEFAULT_DELAY, new Runnable() {
47  
48              @Override
49              public void run() {
50  
51                  final int attempts = shutdownAttempts.incrementAndGet();
52  
53                  if (attempts > MAX_ATTEMPTS) {
54                      callback.onFailure(new Exception("Service could not be shut down in timeout."));
55                      return;
56                  }
57  
58                  shutdown(callback);
59              }
60          });
61  
62      }
63  
64      public ShutdownHelperImpl(final OperationCounter operationCounter, final Concurrency con) {
65          super();
66          this.operationCounter = operationCounter;
67          this.con = con;
68          this.shutdownAttempts = con.newAtomicInteger(0);
69          this.isShutdown = con.newAtomicBoolean(false);
70          this.isShuttingDown = con.newAtomicBoolean(false);
71      }
72  
73  }