View Javadoc
1   package com.jsql.model.suspendable;
2   
3   import com.jsql.model.InjectionModel;
4   import com.jsql.model.exception.JSqlException;
5   import com.jsql.util.LogLevelUtil;
6   import org.apache.logging.log4j.LogManager;
7   import org.apache.logging.log4j.Logger;
8   
9   /**
10   * A thread used to inject database ; stoppable and pausable.
11   */
12  public abstract class AbstractSuspendable {
13      
14      private static final Logger LOGGER = LogManager.getRootLogger();
15  
16      /**
17       * Make the action to stop if true.
18       */
19      private boolean isStopped = false;
20      
21      /**
22       * Make the action to pause if true, else make it unpause.
23       */
24      private boolean isPaused = false;
25  
26      protected final InjectionModel injectionModel;
27      
28      protected AbstractSuspendable(InjectionModel injectionModel) {
29          this.injectionModel = injectionModel;
30      }
31      
32      /**
33       * The pausable/stoppable action.
34       */
35      public abstract String run(Object... args) throws JSqlException;
36  
37      /**
38       * Thread's states Pause and Stop are processed by this method.<br>
39       * - Pause action in infinite loop if invoked while shouldPauseThread is set to true,<br>
40       * - Return stop state.
41       * @return Stop state
42       */
43      public synchronized boolean isSuspended() {
44          // Make application loop until shouldPauseThread is set to false by another user action
45          while (this.isPaused) {
46              try {
47                  this.wait();
48              } catch (InterruptedException e) {
49                  LOGGER.log(LogLevelUtil.IGNORE, e, e);
50                  Thread.currentThread().interrupt();
51              }
52          }
53          return this.isStopped || this.injectionModel.isStoppedByUser();  // Return true if stop requested, else return false
54      }
55      
56      /**
57       * Mark as stopped.
58       */
59      public void stop() {
60          this.unpause();
61          this.isStopped = true;
62      }
63      
64      /**
65       * Mark as paused.
66       */
67      public void pause() {
68          this.isPaused = true;
69      }
70      
71      /**
72       * Mark as unpaused.
73       */
74      public void unpause() {
75          this.isPaused = false;
76          this.resume();  // Restart the action after unpause
77      }
78      
79      /**
80       * Return true if thread is paused, false otherwise.
81       * @return Pause state
82       */
83      public boolean isPaused() {
84          return this.isPaused;
85      }
86      
87      /**
88       * Wake threads.
89       */
90      public synchronized void resume() {
91          this.notifyAll();
92      }
93  }