Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: fe330ccfdc3d9e93412c4e0aae3a990c917f01f1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/*
 * Copyright (c) 2008-2012 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.net4j.util.concurrent;

import org.eclipse.net4j.internal.util.bundle.OM;
import org.eclipse.net4j.util.WrappedException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author Eike Stepper
 * @since 2.0
 */
public abstract class MonitoredThread extends Thread
{
  private MonitoredThread.ThreadMonitor monitor;

  private long timeStamp;

  private boolean shutdown;

  public MonitoredThread(String name, MonitoredThread.ThreadMonitor monitor)
  {
    super(name);
    this.monitor = monitor;
  }

  public long getTimeStamp()
  {
    return timeStamp;
  }

  public boolean isIdleTimeoutExpired(long idleTimeOut)
  {
    if (timeStamp != 0L) // Skip in first loop
    {
      long idle = System.currentTimeMillis() - timeStamp;
      return idle > idleTimeOut;
    }

    return false;
  }

  public void heartBeat()
  {
    if (shutdown)
    {
      throw new ShutdownException();
    }

    timeStamp = System.currentTimeMillis();
  }

  public void shutdown()
  {
    shutdown = true;
  }

  @Override
  public void run()
  {
    monitor.handleStarting(this);

    try
    {
      doRun();
    }
    catch (MonitoredThread.ShutdownException ex)
    {
      return;
    }
    catch (Exception ex)
    {
      OM.LOG.error(ex);
      throw WrappedException.wrap(ex);
    }
    finally
    {
      monitor.handleFinished(this);
    }
  }

  protected abstract void doRun() throws Exception;

  /**
   * @author Eike Stepper
   */
  private static final class ShutdownException extends RuntimeException
  {
    private static final long serialVersionUID = 1L;
  }

  /**
   * @author Eike Stepper
   */
  public static interface ThreadMonitor
  {
    public void handleStarting(MonitoredThread thread);

    public void handleFinished(MonitoredThread thread);
  }

  /**
   * @author Eike Stepper
   */
  public static class MultiThreadMonitor implements MonitoredThread.ThreadMonitor, Runnable
  {
    public static final long SYNCED_START = -1;

    private long idleTimeOut;

    private long startOffset;

    private CountDownLatch startLatch;

    private List<MonitoredThread> threads = new ArrayList<MonitoredThread>();

    /**
     * @param idleTimeOut
     *          The number of milli seconds one of the threads may be idle (i.e. not having called
     *          {@link MonitoredThread#heartBeat()}) before {@link #handleTimeoutExpiration(MonitoredThread)} is called.
     * @param startOffset
     *          The number of milli seconds to sleep between threads are started. Zero means not to sleep and
     *          {@link #SYNCED_START} means that all threads start at the same time by waiting on a shared latch.
     */
    public MultiThreadMonitor(long idleTimeOut, long startOffset)
    {
      this.idleTimeOut = idleTimeOut;
      this.startOffset = startOffset;
      if (startOffset == SYNCED_START)
      {
        startLatch = new CountDownLatch(1);
      }
    }

    /**
     * Same as calling <tt>MonitoredThread(idleTimeOut, SYNCED_START)</tt>.
     */
    public MultiThreadMonitor(long timeOut)
    {
      this(timeOut, SYNCED_START);
    }

    public long getIdleTimeOut()
    {
      return idleTimeOut;
    }

    public void addThread(MonitoredThread thread)
    {
      synchronized (threads)
      {
        threads.add(thread);
      }
    }

    public void handleStarting(MonitoredThread thread)
    {
      if (startLatch != null)
      {
        try
        {
          startLatch.await();
        }
        catch (InterruptedException ex)
        {
          throw WrappedException.wrap(ex);
        }
      }
      else if (startOffset > 0L)
      {
        ConcurrencyUtil.sleep(startOffset);
      }
    }

    public void handleFinished(MonitoredThread thread)
    {
      synchronized (threads)
      {
        threads.remove(thread);
      }
    }

    public void run()
    {
      startupThreads();

      for (;;)
      {
        List<MonitoredThread> idleThreads = new ArrayList<MonitoredThread>();
        synchronized (threads)
        {
          if (threads.isEmpty())
          {
            break;
          }

          for (MonitoredThread thread : threads)
          {
            if (thread.isIdleTimeoutExpired(idleTimeOut))
            {
              idleThreads.add(thread);
            }
          }
        }

        for (MonitoredThread thread : idleThreads)
        {
          handleTimeoutExpiration(thread);
        }
      }

      ConcurrencyUtil.sleep(10);
    }

    protected void handleTimeoutExpiration(MonitoredThread thread)
    {
      synchronized (threads)
      {
        threads.remove(thread);
      }

      shutdownThreads();
      throw new RuntimeException("Idle timeout expired: " + thread.getName()); //$NON-NLS-1$
    }

    private void startupThreads()
    {
      for (MonitoredThread thread : threads)
      {
        thread.start();
      }

      if (startLatch != null)
      {
        startLatch.countDown();
      }
    }

    private void shutdownThreads()
    {
      synchronized (threads)
      {
        for (MonitoredThread t : threads)
        {
          t.shutdown();
        }
      }
    }
  }
}

Back to the top