1: package play.learn.java.concurrent;
2:
3: import java.util.concurrent.BrokenBarrierException;
4: import java.util.concurrent.TimeUnit;
5:
6: public class LearnTimeUnit {
7:
8: public LearnTimeUnit() throws InterruptedException {
9:
10: // assuming we have a long running apps which ran for 2 days 7hours 35minutes 6 seconds
11: long longRunningApplicationDuration = 200102l;
12:
13: System.out.println("duration in nanos " + TimeUnit.SECONDS.toNanos(longRunningApplicationDuration));
14: System.out.println("duration in days " + TimeUnit.SECONDS.toDays(longRunningApplicationDuration));
15: System.out.println("duration in hours " + TimeUnit.SECONDS.toHours(longRunningApplicationDuration));
16: System.out.println("duration in micros " + TimeUnit.SECONDS.toMicros(longRunningApplicationDuration));
17: System.out.println("duration in millis " + TimeUnit.SECONDS.toMillis(longRunningApplicationDuration));
18: System.out.println("duration in minutes " + TimeUnit.SECONDS.toMinutes(longRunningApplicationDuration));
19: System.out.println("duration in seconds " + TimeUnit.SECONDS.toSeconds(longRunningApplicationDuration));
20:
21:
22: TimeUnit[] var = TimeUnit.values();
23: System.out.println("size " + var.length);
24:
25: for (TimeUnit elem : var) {
26: System.out.println(elem.name());
27: }
28:
29: TimeUnit.SECONDS.sleep(10);
30: }
31:
32: public static void main(String[] args) throws InterruptedException {
33: new LearnTimeUnit();
34: }
35:
36: }
TimeUnit provides several helpful methods to convert the time to different unit. You can also download the above source code here.
Next, we will take a look at concurrent exceptions. This exception will become meaningful when we try catch it in the class. For now, we will go through the definition to get a basic understanding of them. Below is a summarization.
BrokenBarrierException
Exception thrown when a thread tries to wait upon a barrier that is in a broken state, or which enters the broken state while the thread is waiting.
CancellationException
Exception indicating that the result of a value-producing task, such as a FutureTask, cannot be retrieved because the task was cancelled.
CompletionException
Exception thrown when an error or other exception is encountered in the course of completing a result or task.
ExecutionException
Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable.getCause() method.
RejectedExecutionException
Exception thrown by an Executor when a task cannot be accepted for execution.
TimeoutException
Exception thrown when a blocking operation times out. Blocking operations for which a timeout is specified need a means to indicate that the timeout has occurred. For many such operations it is possible to return a value that indicates timeout; when that is not possible or desirable then TimeoutException should be declared and thrown.
BrokenBarrierException example, for full source code, you can download it here.
1: package play.learn.java.concurrent;
2:
3: import java.util.concurrent.BrokenBarrierException;
4: import java.util.concurrent.CyclicBarrier;
5:
6: public class LearnBrokenBarrierException {
7:
8: private CyclicBarrier cibai;
9: public static int count = 0;
10:
11: private void manageThread() {
12: cibai = new CyclicBarrier(3);
13:
14: for (int i = 0; i < 3; i++) {
15: new Thread(new Worker(cibai)).start();
16: }
17: }
18:
19: public static void barrierComplete(CyclicBarrier cb) {
20: System.out.println("collating task");
21:
22: if (count == 3) {
23: System.out.println("Exit from system");
24: // comment for finite
25: System.exit(0);
26: }
27: count++;
28:
29: for (int i = 0; i < 3; i++) {
30: new Thread(new Worker(cb)).start();
31: }
32: }
33:
34: public static void main(String[] args) {
35: new LearnBrokenBarrierException().manageThread();
36: }
37:
38: static class Worker implements Runnable {
39:
40: CyclicBarrier cibai;
41:
42: public Worker(CyclicBarrier cb) {
43: this.cibai = cb;
44: }
45:
46: @Override
47: public void run() {
48: doSomeWork();
49: try {
50: if (cibai.await() == 0)
51: LearnBrokenBarrierException.barrierComplete(cibai);
52: } catch (InterruptedException e) {
53: e.printStackTrace();
54: } catch (BrokenBarrierException e) {
55: e.printStackTrace();
56: }
57: }
58:
59: private void doSomeWork() {
60: System.out.println("Doing some work");
61: }
62:
63: }
64:
65: }
66:
CancellationException, ExecutionException, RejectedExecutionException and TimeoutException example, see below. Full source code can be download here.
1: package play.learn.java.concurrent;
2:
3: import java.util.concurrent.Callable;
4: import java.util.concurrent.CancellationException;
5: import java.util.concurrent.ExecutionException;
6: import java.util.concurrent.ExecutorService;
7: import java.util.concurrent.Executors;
8: import java.util.concurrent.TimeUnit;
9: import java.util.concurrent.TimeoutException;
10: import java.util.concurrent.FutureTask;
11:
12: public class LearnCancellationException {
13:
14: public static void main(String[] args) {
15: MyCallable callable1 = new MyCallable(1000);
16: MyCallable callable2 = new MyCallable(2000);
17:
18: FutureTask<String> futureTask1 = new FutureTask<String>(callable1);
19: FutureTask<String> futureTask2 = new FutureTask<String>(callable2);
20:
21: ExecutorService executor = Executors.newFixedThreadPool(2);
22: executor.execute(futureTask1);
23: executor.execute(futureTask2);
24:
25: while (true) {
26: try {
27: if(futureTask1.isDone() && futureTask2.isDone()){
28: System.out.println("Done");
29: //shut down executor service
30: executor.shutdown();
31: return;
32: }
33:
34: // uncomment for cancel
35: //futureTask2.cancel(true);
36:
37: if(!futureTask1.isDone()){
38: //wait indefinitely for future task to complete
39: System.out.println("FutureTask1 output="+futureTask1.get());
40: }
41:
42: System.out.println("Waiting for FutureTask2 to complete");
43: // set a samll range to get timedout exception.
44: String s = futureTask2.get(2000L, TimeUnit.MILLISECONDS);
45: if(s !=null){
46: System.out.println("FutureTask2 output="+s);
47: }
48: } catch (CancellationException e) {
49: e.printStackTrace();
50: } catch (InterruptedException | ExecutionException e) {
51: e.printStackTrace();
52: } catch(TimeoutException e){
53: e.printStackTrace();
54: }
55: }
56:
57: }
58:
59: static class MyCallable implements Callable<String> {
60:
61: private long waitTime;
62:
63: public MyCallable(int timeInMillis) {
64: this.waitTime = timeInMillis;
65: }
66:
67: @Override
68: public String call() throws Exception {
69: Thread.sleep(waitTime);
70: return Thread.currentThread().getName();
71: }
72:
73: }
74:
75: }
76:
CompletionException example, for full source code, you can download it here.
1: public class LearnCompletableFuture {
2:
3: public void learnCompletionException() {
4: try {
5: List<String> list = Arrays.asList("A", "B", "C", "D");
6: list.stream().map(s->CompletableFuture.supplyAsync(() -> s+s))
7: .map(f->f.getNow("Not Done")).forEach(s->System.out.println(s));
8:
9: } catch (CompletionException e) {
10: e.printStackTrace();
11: }
12:
13: }
14:
15: public static void main(String[] args) {
16: LearnCompletableFuture c = new LearnCompletableFuture();
17: c.learnCompletionException();
18: }
19: }
That's it for this article, for the incoming interface and classed until java.util.concurrent which will be publish in the next few articles, until then.
No comments:
Post a Comment