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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
package Torello.Java;

import java.util.Vector;
import java.util.concurrent.CompletionException;

import Torello.Java.StringParse;

/**
 * A helper-class that performs <CODE>Thread</CODE>-managment for the class
 * <CODE>Torello&#46;Java&#46;OSResponse</CODE>
 * 
 * <EMBED CLASS='external-html' DATA-FILE-ID=OSR_HELPER_NOTE>
 * <EMBED CLASS='external-html' DATA-FILE-ID=COMPLETED>
 */
class Completed
{
    /**
     * This is set to {@code TRUE} when {@code 'this'} instance is currently waiting for
     * its {@code Thread's} to complete.
     */
    private boolean waitHasBeenCalled = false;

    /** Maintains a list of the {@code Thread's} that were registered with this class. */
    private Vector<Thread> watchedThreads  = new Vector<>();

    /** Keeps a list of any {@code Exception's} that occur when invoking a {@code Thread} */
    private Vector<Exception> exceptions = new Vector<>();

    /** Keeps a list of {@code Thread's} that have provided a {@code 'finished'} message. */
    private Vector<Boolean> finished = new Vector<>();

    /** A simple, zero-argument, constructor. */
    Completed() { }

    /** Makes sure the {@code Thread's} are cleared out of the internal-storage {@code Vector's} */
    @SuppressWarnings("deprecation")
    protected void finalize()
    {
        watchedThreads.clear(); watchedThreads  = null;
        exceptions.clear();     exceptions      = null;
        finished.clear();       finished        = null;
    }

    /** 
     * Provided a given input {@code Thread} parameter, this method retrieves the
     * {@code Vector}-index location inside the internal-storage {@code Vector's} for that
     * {@code Thread}.
     * 
     * @param thread This may be any Java {@code Thread} instance, but only ones which were
     * registered previously with this {@code Completed} instance can be found in the
     * internal-storage.
     * 
     * @return Returns the index / location within the internal-storage {@code Vector's} of the
     * provided {@code Thread}.
     */
    protected synchronized int find(Thread thread)
    {
        for (int i=0; i < watchedThreads.size(); i++)
            if (thread == watchedThreads.elementAt(i))
                return i;

        return -1;
    }

    /**
     * Fully resets the internal state of this instance of {@code Completed}.  Afterwards, the
     * behavior of {@code 'this'} instance should be identical to one where {@code 'this'} had just
     * been created by the constructor.
     */
    synchronized void clear()
    {
        watchedThreads.clear();
        exceptions.clear();
        finished.clear();

        waitHasBeenCalled = false;
    }

    /**
     * This takes {@code 'this'} instance of {@code 'Completed'} and removes any registered
     * exceptions that have been reported to {@code 'this'} instance, from the internal storage
     * {@code Vector's}.  It also removes any / all responses that this instance has received
     * from the registered {@code Thread's}.
     * 
     * <BR /><BR /><B>NOTE:</B> Unlike method {@link #clear()}, this method <I><B>does not remove
     * the registered {@code Thread's}, themselves!</B></I>.
     */
    synchronized void reset()
    {
        for (int i=0; i < exceptions.size(); i++) exceptions.setElementAt(null, i);

        for (int i=0; i < finished.size(); i++) finished.setElementAt(Boolean.FALSE, i);
    }

    /**
     * Converts a {@code java.lang.Thread} to a {@code String} using it's {@code name} and
     * {@code id} fields.
     * 
     * @param thread This may be any java {@code Thread}.
     * 
     * @return a Java {@code String} that contains the values in {@code Thread.getID()} and
     * also {@code Thread.getName()}.  If {@code Thread.getName()} returns null, then the name
     * printed will simply be {@code "Name Not Available"}
     */
    static String nameAndId(Thread thread)
    {
        return "Thread [ID: " + thread.getId() + ", Name: " +
            ((thread.getName() != null) ? thread.getName() : "Name Not Available") + "]";
    }

    /**
     * Registers another {@code Thread} with this monitor.
     * 
     * <BR /><BR /><B>NOTE:</B> Once a {@code Thread} has been registered, this class will accept
     * {@code 'finished'} and {@code 'exceptionWasThrown'} messages (invocations) from that
     * {@code Thread} - <I>once a {@code waitForCompletionOf...} has been called.</I>
     *
     * @param thread This may be any Java {@code Thread}.  This thread will be registered with this
     * class.  Registering allows {@code Thread's} to send {@code 'finished'} messages to this 
     * monitor class (by-way-of calling this class {@code Completed.finished} method.
     *
     * @throws IllegalArgumentException If the {@code 'thread'} parameter instance has already been
     * registered with this instance of {@code 'Completed'} (using this {@code addThread(Thread)}
     * method, then {@code IllegalArgumentException} will throw.
     *
     * @throws IllegalThreadStateException If an attempt is made to add a {@code Thread} to
     * this instance of {@code Completed} (using this method, {@code Completed.addThread}),
     * <I><B>*after*</I></B> a call to one of the {@code Completed.waitForCompletion...} methods
     * have been invoked.  Once a call to a {@code wait} method has been made, new
     * {@code Thread's} to monitor cannot be added using this method until all previously added
     * thread's have sent {@code 'finished'} messages, and a call to either {@code clear()} or
     * {@code reset()} has been made.
     */
    synchronized void addThread(Thread thread)
    {
        if (find(thread) != -1) throw new IllegalArgumentException(
            "This " + nameAndId(thread) + " has already been added to this instance of " +
            "class 'Completed'."
        );

        if (waitHasBeenCalled) throw new IllegalThreadStateException(
            "This instance of Completed has already been issued a waitForCompletion... method " +
            "invocation, and is not currently accepting new Thread's to add to it's internal " +
            "list of threads to wait on.  In order for class Completed to wait for a thread to " +
            "finish, that thread must be registered with this instance (using this method " +
            "'addThread') *BEFORE* a call to waitForCompletion is made."
        );

        watchedThreads.add(thread);
        exceptions.add(null);
        finished.add(Boolean.FALSE);
    }

    /**
     * This method may be invoked to tell this instance of {@code Completed} that a particular
     * {@code Thread} has thrown an {@code Exception}.  The thrown {@code 'exception'} will be
     * recorded, and may even be retrieved later (or thrown), if needed.
     *
     * <BR /><BR />Internally, the {@code Exception} will be stored and associated with the
     * {@code 'thread'} parameter.
     * 
     * <BR /><BR /><B STYLE='color: red;'>IMPORTANT:</B> Even after an {@code 'exception throw'}
     * message is sent to an instance of this class (using this method,
     * {@code 'Completed.exceptionWasThrown'}), {@code Completed} will still wait for the
     * {@code Thread} that registered this exception to finish.  Regardless of reported-exceptions,
     * it is always necessary to send {@code 'finished'} messages to this class (using method
     * {@code 'Completed.finished'}) for each {@code Thread} that this instance is waiting on.
     *
     * @param thread This is the {@code Thread} that has thrown the {@code 'exception'}
     *
     * @param exception This is the {@code Exception} that was thrown.
     *
     * @return This method will return {@code TRUE}, unless the {@code 'thread'} parameter has
     * already had an exception reported about it.  It is neither mandatory nor critical to heed
     * this return-value.  It just reports whether this is the <B><I>first</B></I> 
     * {@code 'Exception'} reported about the {@code 'thread'} parameter.
     *
     * @throws IllegalStateException This exception throws if this instance of
     * {@code 'Completed'} has not received a call to one of the {@code waitForCompletion...}
     * methods already.  Reporting that one of the {@code Thread's} on which this class
     * is <I>"waiting for Completion"</I> has thrown an exception, without first telling this
     * instance to wait will cause {@code IllegalStateException}.
     *
     * @throws IllegalArgumentException This exception throws if the {@code 'thread'} parameter
     * was not actually registered with this instance of {@code 'Completed'}.  In order for an
     * instance of {@code Completed} to heed <B>either</B> {@code 'finished'} <B>or</B>
     * {@code 'exception'} messages from a {@code Thread}, that {@code Thread} must first have
     * been registered with the instance using the {@code addThread(Thread)} method.
     *
     * @see #addThread(Thread)
     * @see #find(Thread)
     */
    synchronized boolean exceptionWasThrown(Thread thread, Exception exception)
    {
        if (! waitHasBeenCalled) throw new IllegalStateException(
            "An 'exception-throw' message has been sent to this instance of Completed by " +
            nameAndId(thread) + ", but unfortunately, no invocations of 'wait' have been issued " +
            "to this class yet.  Exception-throw messages (which are explicitly sent by calling " +
            "this method, 'exceptionWasThrown') CANNOT be sent until one of the " +
            "'waitForCompletion...' methods have been invoked."
        );

        int pos = find(thread);

        if (pos == -1) throw new IllegalArgumentException(
            "The " + nameAndId(thread) + ", for which this this method 'exceptionWasThrown' " +
            "was invoked has not been registered with this instance of 'Completed' (using the " +
            "Completed.addThread(...) method prior to the calling 'exceptionWasThrown'."
        );

        boolean ret = exceptions.elementAt(pos) == null;

        exceptions.setElementAt(exception, pos);

        return ret;
    }

    /**
     * Informs this {@code 'Completed'} class instance that the {@code 'thread'} instance has
     * run to completion.  Attempts to wake up the monitor {@code Thread} running this 
     * instance of {@code Completed} using {@code this.notify()} to check if <I><B>all
     * {@code Thread's} that are being monitored have completed</I></B>
     *
     * @param thread This is the {@code Thread} that has completed it's task.
     *
     * @throws IllegalStateException This exception throws if this instance of
     * {@code 'Completed'} has not received a call to one of the {@code waitForCompletion...}
     * methods already.  Reporting that one of the {@code Thread's} on which this class
     * is <I>"waiting for Completion"</I> has finished, without first telling this instance
     * to wait will cause {@code IllegalStateException}.
     *
     * @throws IllegalArgumentException This exception throws if the {@code 'thread'} parameter
     * was not actually registered with this instance of {@code 'Completed'}.  In order for an
     * instance of {@code Completed} to heed <B>either</B> {@code 'finished'} <B>or</B>
     * {@code 'exception'} messages from a {@code Thread}, that {@code Thread} must first have
     * been registered with the instance using the {@code Completed.addThread(Thread)} method.
     *
     * @throws IllegalThreadStateException If a <I>second finished message</I> is sent for a
     * particular registered-{@code Thread} (as in registered earlier through the {@code addThread}
     * method) then this exception will throw.  Unless calls to either {@code reset()} or
     * {@code clear()} are made, multiple invocations of {@code 'finished'} cannot be made using
     * the exact same {@code Thread} parameter.
     *
     * @see #addThread(Thread)
     * @see #find(Thread)
     */
    synchronized void finished(Thread thread)
    {
        if (! waitHasBeenCalled) throw new IllegalStateException(
            "A 'finished' message has been sent to this instance of Completed by " +
            nameAndId(thread) + ", but unfortunately, no invocations of 'wait' have been issued " +
            "to this class yet.  Finished messages (which are explicitly sent by calling this " +
            "method, 'finished') CANNOT be sent until one of the 'waitForCompletion...' methods " +
            "have been invoked."
        );

        int pos = find(thread);

        if (pos == -1) throw new IllegalArgumentException(
            "The " + nameAndId(thread) + " for which this this method 'finished' was invoked " +
            "was not not registered using this class 'addThread' method prior to calling " + 
            "'finished'"
        );

        if (finished.elementAt(pos) == Boolean.TRUE) throw new IllegalThreadStateException(
            "A 'finished' message has already been sent by " + nameAndId(thread) + " to this " +
            "instance of Complete.  This instance must be issued a 'clear' or 'reset' " +
            "message (by calling methods with these names) first before reporting that this " +
            "Thread has finished again."
        );

        finished.setElementAt(Boolean.TRUE, pos);

        // THE NOTIFY IS DONE HERE
        this.notify();
    }

    /**
     * This method will run until all {@code Thread's} have finished their assignments.
     * 
     * <BR /><BR />This method shall:
     *
     * <BR /><BR /><OL CLASS=JDOL>
     * <LI> First, this method checks whether all registered {@code Thread's} (which must have 
     *      been registered using the {@code addThread(Thread)} method) have already reported 
     *      {@code 'finished'} messages using the method {@code finished(Thread)}.  If all
     *      registered {@code Thread's} have finished, this method shall exit gracefully.
     *      <BR /><BR />
     * </LI>
     * <LI> Next, if there are registered {@code Thread's} that have not completed, then this 
     *      method shall make a call to {@code this.wait()}, and halt the current {@code Thread's}
     *      progress until {@code 'this'} instance receives a {@code notify()} call from the
     *      JVM's {@code Object.notify()} mechanism.  It is important to note that when any other
     *      method calls this class' {@code 'finished(Thread)'} method, <I>the code in this class
     *      will call {@code this.notify()}</I> and wake up any other dormant or 'sleeping'
     *      {@code Thread's}.  When all {@code Thread's} have reported {@code 'finished(Thread)'}
     *      <I>then and only then</I> shall this method shall exit.  If there are other threads
     *      that need to complete, then this method will invoke {@code this.wait()} until they
     *      have.
     * </LI>
     * </OL>
     *
     * @throws IllegalStateException If this method is invoked, but no {@code Thread's} have
     * been registered with this instance of {@code 'Completed'} (using the
     * {@code Completed.addThread} method), then this exception will throw.  This is because
     * there would be nothing for this method to do, as in this case there would be no registered
     * {@code Thread's} to wait on.
     *
     * @throws IllegalThreadStateException If this instance of completed has already been asked to
     * {@code 'wait'} for thread completion, then this exception shall throw.  A {@code 'wait'}
     * message should only be invoked on an instance of {@code Completed} once.
     * 
     * <BR /><BR />Note that both the {@link #reset()} and the {@link #clear()} methods shall reset
     * this instance's flags - regardless of whether a {@code 'wait'} request has already been
     * issued.
     *
     * @throws If the JVM internal process is interrupted by some other {@code Thread} then an
     * {@code InterruptedException} will throw.
     */
    synchronized void waitForCompletionOfAllThreads() throws InterruptedException
    {
        if (watchedThreads.size() == 0) throw new IllegalStateException(
            "This instance of Complete has not received any calls to its 'addThread' method, " +
            "and therefore does not have any Thread's to wait on for completion."
        );

        if (waitHasBeenCalled) throw new IllegalThreadStateException(
            "A 'wait' method has already been invoked on this class.  'reset' or 'clear' must " +
            "be invoked, or a new instance of Completed must be created before calling any " +
            "more 'waitForCompletion...' methods."
        );

        waitHasBeenCalled = true;

        for (Thread thread : watchedThreads) thread.start();

        while (true)
        {
            boolean allThreadsHaveFinished = true;

            HERE:
            for (Boolean threadIsFinished : finished)

                if (! threadIsFinished.booleanValue())
                {
                    allThreadsHaveFinished = false;
                    break HERE;
                }

            if (allThreadsHaveFinished) return; // All Tasks have finished!

            else this.wait();   // Let another Thread start up!
                                // There are more tasks that aren't done!
        }
    }

    /**
     * This method will run until the specified threads have finished their assignments.
     * 
     * <BR /><BR />This method shall:
     *
     * <BR /><BR /><OL CLASS=JDOL>
     * <LI> First, this method checks whether the {@code Thread's} which are listed by parameter
     *      {@code 'threads'} (<B><I>each</I></B> of which <B><I>must</I></B> have 
     *      registered using the {@code addThread(Thread)} method) have already reported 
     *      {@code 'finished'} messages using the method {@code finished(Thread)}.  If every
     *      {@code Thread} listed by {@code Varargs} parameter {@code 'threads'} has finished,
     *      then this method shall simply exit gracefully.
     *      <BR /><BR />
     * </LI>
     * <LI> Next, if some of the {@code Thread's} listed in parameter {@code 'threads'} have not 
     *      completed, then this method shall make a call to {@code this.wait()}, and halt the 
     *      current {@code Thread's} progress until {@code 'this'} instance receives a
     *      {@code notify()} call from the JVM's {@code Object.notify()} mechanism.  It is
     *      important to note that when any other method calls this class'
     *      {@code 'finished(Thread)'} method, <I>the code in this class will call
     *      {@code this.notify()}</I> and wake up any other dormant or 'sleeping'
     *      {@code Thread's} that are using {@code 'this'} object as a waiting-lock.  When all
     *      {@code Thread's} listed as input have reported {@code 'finished(Thread)'} - <I>then and
     *      and only then</I> shall this method exit.  When {@code 'this'} instance receives a
     *      JVM {@code notify()} message, if there are other {@code Thread's} that still need to
     *      complete, then this method shall invoke {@code this.wait()} again (until all listed
     *      {@code Thread's} have completed).
     * </LI>
     * </OL>
     *
     * @param threads This {@code Varargs} parameter shall take a list of {@code Thread's} for this
     * instance of {@code Completed} to check-on and wait-for completion.  It is important to note
     * that the {@code Thread's} in this parameter <I>must have been registered with this class</I>
     * (using the {@code addThread(Thread)} method, or else an {@code IllegalArgumentException} 
     * shall throw.
     *
     * @throws IllegalStateException If this method is invoked, but no {@code Thread's} have
     * been registered with this instance of {@code 'Completed'} (using the
     * {@code Completed.addThread} method), then this exception will throw.  This is because
     * there would be nothing for this method to do, as in this case there would be no registered
     * {@code Thread's} to wait on.
     *
     * @throws IllegalThreadStateException If this instance of completed has already been asked to
     * {@code 'wait'} for thread completion, then this exception shall throw.  A {@code 'wait'}
     * message should only be invoked on an instance of {@code Completed} once.
     * 
     * <BR /><BR />Note that both the {@link #reset()} and the {@link #clear()} methods shall reset
     * this instance's flags - regardless of whether a {@code 'wait'} request has already been
     * issued.
     *
     * @throws IllegalArgumentException If any of the {@code Thread's} listed in {@code 'threads'}
     * Var-Args Parameter were not added to this class using the {@code addThread(Thread)}
     * method, then an {@code IllegalArgumentException} will throw.
     *
     * @throws NullPointerException if any of the {@code 'threads'} passed to the Varargs
     * parameter are null references.
     *
     * @throws If the JVM internal process is interrupted by some other {@code Thread} then an
     * {@code InterruptedException} will throw.
     */
    synchronized void waitForCompletionOf(Thread... threads) throws InterruptedException
    {
        if (watchedThreads.size() == 0) throw new IllegalStateException(
            "This instance of Complete has not received any calls to its 'addThread' method, " +
            "and therefore does not have any Thread's to wait on for completion."
        );

        if (waitHasBeenCalled) throw new IllegalThreadStateException(
            "A 'wait' method has already been invoked on this class.  'reset' must be " +
            "invoked, or a new instance of Completed must be created"
        );

        int[] posArr = new int[threads.length];

        for (int i=0; i < threads.length; i++)
        {
            if (threads[i] == null) throw new NullPointerException(
                "The " + i + StringParse.ordinalIndicator(i) + " element of the input Thread-" +
                "Array was null"
            );

            posArr[i] = find(threads[i]);

            if (posArr[i] == -1) throw new IllegalArgumentException(
                "One of the threads passed to this method was never registered using the " +
                "'addThread' method."
            );
        }

        waitHasBeenCalled = true;

        for (int threadIndex : posArr) watchedThreads.elementAt(threadIndex).start();

        while (true)
        {
            boolean allThreadsHaveFinished = true;

            HERE:
            for (int pos : posArr)

                if (! finished.elementAt(pos).booleanValue()) 
                {
                    allThreadsHaveFinished = false;
                    break HERE;
                }

            if (allThreadsHaveFinished) return; // All Tasks have finished!

            else this.wait();   // Let another Thread start up!
                                // There are more tasks that aren't done!
        }
    }

    /**
     * This method throws a wrapper-{@code Exception} ({@code CompletionException}) that wraps any
     * {@code Exceptions} which were thrown by the other {@code Thread's} which have added
     * themselves to this class - <I>and have reported those exceptions to this instance</I>
     *
     * @throws CompletionException An 'unchecked' {@code Exception} (inherits from class 
     * {@code java.lang.RuntimeException}) which wraps any exception which has been thrown and
     * reported to {@code 'this'} instance, by the {@code Thread's} registered to this instance.
     */
    void ifExceptionThrowException()
    {
        int pos=0;

        while (pos < exceptions.size())

            if (exceptions.elementAt(pos) != null) break;
            else pos++;

        if (pos == exceptions.size()) return;

        Thread thread      = watchedThreads.elementAt(pos);
        String name        = thread.getName();
        String description = "Thread ID: [" + thread.getId() + "]";

        if (name != null) description += ", Thread Name: [" + name + "]";

        for (Exception e : exceptions) if (e != null) throw new CompletionException(
            "There was an exception when attempting to execute this command.  Please see this " +
            "exception's 'Throwable.getCause()' method for more details." + description, e
        );
    }
}