View Javadoc

1   /*
2    Copyright (C) 2007 Grid Systems, S.A.
3   
4    This library is free software; you can redistribute it and/or
5    modify it under the terms of the GNU Lesser General Public
6    License as published by the Free Software Foundation; either
7    version 2.1 of the License, or (at your option) any later version.
8   
9    This library is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12   Lesser General Public License for more details.
13  
14   You should have received a copy of the GNU Lesser General Public
15   License along with this library; if not, write to the Free Software
16   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
17  */
18  package com.gridsystems.nextgrid.api.pom;
19  
20  import nextgrid.api.pom.ProcessController;
21  import nextgrid.api.pom.ProcessException;
22  
23  /**
24   * Controller wrapper around a worker thread.
25   */
26  class ThreadController implements ProcessController {
27    /** Context. */
28    private final ProcessContext ctx;
29    /** Controlled algorithm. */
30    private final Enactable e;
31    /** The actual thread. */
32    private EnactionWorker worker;
33  
34    /**
35     * Creates a new instance.
36     *
37     * @param ctx The context
38     * @param e   The enaction algorithm
39     */
40    public ThreadController(ProcessContext ctx, Enactable e) {
41      this.ctx = ctx;
42      this.e = e;
43    }
44  
45    /**
46     * {@inheritDoc}
47     */
48    public void cancel() throws ProcessException, InterruptedException {
49      if (worker != null) {
50        ctx.cancel();
51        worker.join();
52      }
53    }
54  
55    /**
56     * {@inheritDoc}
57     */
58    public State getState() {
59      return ctx.getState();
60    }
61  
62    /**
63     * {@inheritDoc}
64     */
65    public void pause() throws ProcessException, InterruptedException {
66      if (worker != null) {
67        ctx.pause();
68        worker.join();
69      }
70    }
71  
72    /**
73     * {@inheritDoc}
74     */
75    public void resume() throws ProcessException {
76      ctx.resume();
77      if (worker == null) {
78        worker = ctx.createWorkerThread(e);
79        worker.start();
80      }
81    }
82  
83    /**
84     * {@inheritDoc}
85     */
86    public void start() {
87      if (worker == null) {
88        worker = ctx.createWorkerThread(e);
89        worker.start();
90      }
91    }
92  
93    /**
94     * {@inheritDoc}
95     */
96    public void join() throws ProcessException, InterruptedException {
97      if (worker != null) {
98        worker.join();
99        worker.checkError();
100     }
101   }
102 
103   /**
104    * {@inheritDoc}
105    */
106   public void run() throws ProcessException, InterruptedException {
107     start();
108     join();
109   }
110 }