-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJava_Executor_Service_class.java
More file actions
279 lines (224 loc) · 7.09 KB
/
Java_Executor_Service_class.java
File metadata and controls
279 lines (224 loc) · 7.09 KB
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
import java.util.*;
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.ArrayDeque;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
class ComputeTask extends RecursiveTask<Integer>{
int start;
int end;
ComputeTask(int start,int end){
this.start=start;
this.end=end;
}
protected Integer compute(){
if(end-start<=4){
int totalsum=0;
for(int i=start;i<=end;i++){
totalsum+=i;
}
return totalsum;
}else{
//split the task
int mid=(start+end)/2;
ComputeTask lefttask= new ComputeTask(start, mid);
ComputeTask righttask= new ComputeTask(mid+1, end);
//fork the subttasks for parallel execution
lefttask.fork();
righttask.fork();
//combine the result of subtasks
int leftResult= lefttask.join();
int rightResult = righttask.join();
return leftResult+rightResult;
}
}
}
class Java_Executor_Service_class{
public static void main(String[] args){
ExecutorService executor1 = Executors.newFixedThreadPool(5);
//#used whenn need to create a Threadpoolexecutor with fixed no of thread, needed when we have exact info about how many async task
executor1.submit(()-> "this is the new Async task");
// ExecutorService executor1 = Executors.newCachedThreadPool(); #create a new Thread dynamically as needed, good for handling burst of short Lived tasks
// executor1.submit(()-> "this is the new Async task");
// ForkJoinPool pool = ForkJoinPool.commonPool();
// Future<Integer> futureObj = pool.submit(new ComputeTask(0, 100));
// try {
// System.out.println(futureObj.get());
// } catch (Exception e) {
// // TODO: handle exception
// }
//Video 38 Concept and coding
// ExecutorService poolObj = Executors.newFixedThreadPool(5);
// poolObj.submit(()->{
// System.out.println("Thread going to start its work");
// });
// poolObj.shutdown();
// poolObj.submit(()->{
// System.out.println("Thread going to start its work");
// }); //Exception in thread "main" java.util.concurrent.RejectedExecutionException:
//usercase1
// ExecutorService poolObj = Executors.newFixedThreadPool(5);
// poolObj.submit(()->{
// try{
// Thread.sleep(5000);
// }catch(Exception e){
// }
// System.out.println("Thread going to start its work");
// });
// poolObj.shutdown();
// System.out.println("Main thread unblocked and finished processing");
// /*Main thread unblocked and finished processing
// Thread going to start its work*/
//usecase2
// ExecutorService poolObj = Executors.newFixedThreadPool(5);
// poolObj.submit(()->{
// try{
// Thread.sleep(5000);
// }catch(Exception e){
// }
// System.out.println("Thread going to start its work");
// });
// poolObj.shutdown();
// try{
// boolean isTerminated = poolObj.awaitTermination(2,TimeUnit.SECONDS);
// System.out.println("is Terminated:"+ isTerminated);
// }catch(Exception e){
// }
// System.out.println("Main thread is completed");
/*is Terminated:false
Main thread is completed
Thread going to start its work*/
//uusecase3
// ExecutorService poolObj = Executors.newFixedThreadPool(5);
// poolObj.submit(()->{
// try{
// Thread.sleep(15000);
// }catch(Exception e){
// }
// System.out.println("task completed");
// });
// poolObj.shutdownNow();
// System.out.println("Main thread is completed");
/*Main thread is completed
task completed*/
ScheduledExecutorService poolObjA = Executors.newScheduledThreadPool(5);
poolObjA.schedule(()->{
System.out.println("hello");
},5,TimeUnit.SECONDS);
//hello -> printed by 5 second delay
// ScheduledExecutorService poolObj = Executors.newScheduledThreadPool(5);
// Future<String> futureObj = poolObj.schedule(()->{
// return "hello";
// },5,TimeUnit.SECONDS);
// try {
// System.out.println(futureObj.get());
// } catch (Exception e) {
// // TODO: handle exception
// }
ScheduledExecutorService poolObj = Executors.newScheduledThreadPool(5);
poolObj.scheduleAtFixedRate(()->{
System.out.println("hello");
},3,5,TimeUnit.SECONDS);
/*hello
hello
hello
// */
// ScheduledExecutorService poolObj = Executors.newScheduledThreadPool(5);
// Future<?> futureobj= poolObj.scheduleAtFixedRate(()->{
// System.out.println("hello");
// },3,5,TimeUnit.SECONDS);
// try {
// Thread.sleep(10000);
// futureobj.cancel(true);
// } catch (Exception e) {
// // TODO: handle exception
// }
//ThreadLocal video39
//-------------------------------------------------------------------
//ThreadLocal<String> threadLocalObj = new ThreadLocal<>();
// threadLocalObj.set(Thread.currentThread().getName());
// Thread t1= new Thread(()->{
// threadLocalObj.set(Thread.currentThread().getName());
// System.out.println("Task1");
// });
// t1.start();
// try {
// Thread.sleep(2000);
// } catch (Exception e) {
// // TODO: handle exception
// }
// System.out.println("Main Thread: "+threadLocalObj.get());
/*Task1
Main Thread: main */
//Cleaning up if reusing the thread
// ThreadLocal<String> threadLocalObj = new ThreadLocal<>();
// ExecutorService poolObj = Executors.newFixedThreadPool(5);
// poolObj.submit(()->{
// threadLocalObj.set(Thread.currentThread().getName());
// });
// for(int i=1;i<15;i++){
// poolObj.submit(()->{
// System.out.println(threadLocalObj.get());
// });
// }
/*null
null
null
null
pool-1-thread-1
null
null
null
null
pool-1-thread-1
null
null
null
null */
//so how you can clean thread local object b4 it is assigned to another task
ThreadLocal<String> threadLocalObj = new ThreadLocal<>();
ExecutorService poolObj = Executors.newFixedThreadPool(5);
poolObj.submit(()->{
threadLocalObj.set(Thread.currentThread().getName());
threadLocalObj.remove();
});
for(int i=1;i<15;i++){
poolObj.submit(()->{
System.out.println(threadLocalObj.get());
});
}
/*C:\Users\KumarHimansh\Desktop\edit_hsk\TechieDelight>java Java_Prac
null
null
null
null
null
null
null
null
null
null
null
null
null
null */
//Virtual thread vs Platform thread
//Moto: to get higher Throughput not latency
}
}