1 | package felix.society; |
2 | |
3 | import java.util.ArrayList; |
4 | import java.util.concurrent.ExecutorService; |
5 | import java.util.concurrent.Executors; |
6 | import java.util.concurrent.Future; |
7 | |
8 | /** |
9 | * A concurrent task. |
10 | * @author czhang |
11 | * |
12 | */ |
13 | public abstract class Task { |
14 | |
15 | /** |
16 | * Number of runs of this task. |
17 | */ |
18 | private int nRuns = 1; |
19 | |
20 | /** |
21 | * Type of task \in {TASKSET, TASKLIST, TASK} |
22 | * @author czhang |
23 | * |
24 | */ |
25 | public static enum TaskType {TASKSET, TASKLIST, TASK} |
26 | |
27 | /** |
28 | * A thread poll that only contains very very cheap threads (to |
29 | * support TaskSet > TaskList1, TaskList2 structure) |
30 | */ |
31 | public static ExecutorService softpool = Executors.newFixedThreadPool(1000); |
32 | |
33 | /** |
34 | * Type of this task. |
35 | */ |
36 | private TaskType type; |
37 | |
38 | /** |
39 | * If this task is a task list or task set, all subtasks. |
40 | */ |
41 | ArrayList<Task> subTasks = new ArrayList<Task>(); |
42 | |
43 | /** |
44 | * What worker is currently running? |
45 | */ |
46 | public Worker currentWorker = null; |
47 | |
48 | /** |
49 | * What future is currently running (used for join). |
50 | */ |
51 | public Future currentFuture = null; |
52 | |
53 | /** |
54 | * The constructor. |
55 | * @param _type |
56 | */ |
57 | public Task(TaskType _type){ |
58 | type = _type; |
59 | } |
60 | |
61 | /** |
62 | * |
63 | * @return |
64 | */ |
65 | public TaskType getType(){ |
66 | return type; |
67 | } |
68 | |
69 | public Task(TaskType _type, Integer _nRuns){ |
70 | type = _type; |
71 | nRuns = _nRuns; |
72 | } |
73 | |
74 | public void addSubTask(Task _task){ |
75 | this.subTasks.add(_task); |
76 | } |
77 | |
78 | /** |
79 | * Execute this task. |
80 | * |
81 | * @param pool The thread pool |
82 | * @throws Exception |
83 | */ |
84 | public void execute(ExecutorService pool) throws Exception{ |
85 | |
86 | for(int i=0;i<nRuns;i++){ |
87 | if(this.type == TaskType.TASK){ |
88 | currentWorker = this.generateWorker(); |
89 | currentFuture = pool.submit(currentWorker); |
90 | currentFuture.get(); |
91 | }else{ |
92 | currentWorker = this.generateWorker(pool); |
93 | currentFuture = softpool.submit(currentWorker); |
94 | currentFuture.get(); |
95 | } |
96 | } |
97 | |
98 | } |
99 | |
100 | /** |
101 | * Generate worker for TASK (threads). |
102 | * @return |
103 | */ |
104 | public abstract Worker generateWorker(); |
105 | |
106 | /** |
107 | * Generate worker for TASKLIST, TASKSET (threads). |
108 | * @param pool The thread pool in which subtasks will run. |
109 | * @return |
110 | */ |
111 | public abstract Worker generateWorker(ExecutorService pool); |
112 | |
113 | |
114 | |
115 | |
116 | } |