1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* |
5 |
*/ |
6 |
|
7 |
package jsr166y.forkjoin; |
8 |
import java.util.*; |
9 |
import java.util.concurrent.*; |
10 |
import java.util.concurrent.atomic.*; |
11 |
|
12 |
/** |
13 |
* A minimal skeleton for AsyncActions. Instances of BasicAsyncAction |
14 |
* maintain a single atomic integer task state that may be used to |
15 |
* control activities. Task state is initially zero, or negative if |
16 |
* this task has been cancelled. Once negative, the value cannot be |
17 |
* changed. |
18 |
*/ |
19 |
public abstract class BasicAsyncAction extends AsyncAction { |
20 |
/** |
21 |
* Gets the task state, which is initially zero, or negative if |
22 |
* this task has been cancelled. Once negative, the value cannot |
23 |
* be changed. |
24 |
* @return task state |
25 |
*/ |
26 |
protected final int getTaskState() { |
27 |
return status; |
28 |
} |
29 |
|
30 |
/** |
31 |
* Atomically sets the task state to the given nonnegative updated |
32 |
* value if the current value is non-negative and equal to the |
33 |
* expected value. |
34 |
* @param expect the expected value |
35 |
* @param update the new value |
36 |
* @return true if successful |
37 |
*/ |
38 |
protected final boolean compareAndSetTaskState(int expect, int update) { |
39 |
return update >= 0 && casStatus(expect, update); |
40 |
} |
41 |
|
42 |
/** |
43 |
* Sets the task state to the given nonnegative value, assuming |
44 |
* that no other thread is concurrently accessing this task. The |
45 |
* effects under any other usage are undefined. This method is |
46 |
* typically only useful for initializing state values. |
47 |
* @param value the new value |
48 |
* @throws IllegalArgumentException if value negative |
49 |
*/ |
50 |
protected final void setTaskState(int value) { |
51 |
if (value < 0) throw new IllegalArgumentException(); |
52 |
setStatus(value); |
53 |
} |
54 |
|
55 |
/** |
56 |
* Sets task state to indicate completion |
57 |
*/ |
58 |
public void finish() { |
59 |
setDone(); |
60 |
} |
61 |
|
62 |
/** |
63 |
* Sets task state to indicate completion with the given exception |
64 |
*/ |
65 |
public void finishExceptionally(Throwable ex) { |
66 |
checkedSetDoneExceptionally(ex); |
67 |
} |
68 |
|
69 |
final boolean exec() { |
70 |
if (status >= 0) { |
71 |
try { |
72 |
compute(); |
73 |
} catch(Throwable rex) { |
74 |
setDoneExceptionally(rex); |
75 |
} |
76 |
} |
77 |
return false; |
78 |
} |
79 |
|
80 |
} |