a0ac1546eae5b847b2d25f21e41c8cf147e7f3df
[JavaForFun] /
1 package de.test.thread.executor.future;
2
3 import java.util.concurrent.Callable;
4 import java.util.concurrent.ExecutionException;
5 import java.util.concurrent.FutureTask;
6 import java.util.concurrent.TimeUnit;
7 import java.util.concurrent.TimeoutException;
8
9
10 public class FutureTaskExample {
11         
12         public Car test() {
13                 Car carResult = null;
14                 FutureTask<Car> task = new FutureTask<>(new Callable<Car>() {
15
16                         @Override
17                         public Car call() throws Exception {
18                                 return new Car(99);
19                         }
20
21                 });
22
23                 new Thread(task).start();
24
25                 try {
26                         carResult = task.get(1000, TimeUnit.MILLISECONDS);
27                 } catch (InterruptedException e) {
28                         Thread.currentThread().interrupt();
29                 } catch (ExecutionException e) {
30                         throw launderThrowable(e);
31                 } catch (TimeoutException e) {
32                         System.out.println("Timeout");
33                 } finally {
34                         task.cancel(true);
35                 }
36
37                 return carResult;
38         }
39
40         public static class Car {
41
42                 final int id;
43
44                 public Car(int id) {
45                         this.id = id;
46                 }
47         }
48
49         private RuntimeException launderThrowable(final Throwable exception) {
50                 exception.printStackTrace();
51                 if (exception instanceof RuntimeException)
52                         return (RuntimeException)exception;
53                 else if (exception instanceof Error)
54                         throw (Error)exception;
55                 else
56                         throw new IllegalStateException("Not unchecked", exception);
57         }
58
59 }