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