OnJava8-Examples/tasks/ActiveObjectDemo.java

90 lines
2.3 KiB
Java
Raw Normal View History

2016-01-25 18:05:55 -08:00
// tasks/ActiveObjectDemo.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// Can only pass constants, immutables, "disconnected
// objects," or other active objects as arguments
2016-01-25 18:05:55 -08:00
// to asynch methods
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
import java.util.*;
public class ActiveObjectDemo {
private ExecutorService ex =
Executors.newSingleThreadExecutor();
2016-01-25 18:05:55 -08:00
private SplittableRandom rand = new SplittableRandom(47);
2015-06-15 17:47:35 -07:00
// Insert a random delay to produce the effect
// of a calculation time:
private void pause(int factor) {
try {
TimeUnit.MILLISECONDS.sleep(
100 + rand.nextInt(factor));
} catch(InterruptedException e) {
2015-11-03 12:00:44 -08:00
System.out.println("sleep() interrupted");
2015-06-15 17:47:35 -07:00
}
}
public Future<Integer>
calculateInt(final int x, final int y) {
return ex.submit(() -> {
2015-11-03 12:00:44 -08:00
System.out.println("starting " + x + " + " + y);
2015-06-15 17:47:35 -07:00
pause(500);
return x + y;
});
}
public Future<Float>
calculateFloat(final float x, final float y) {
return ex.submit(() -> {
2015-11-03 12:00:44 -08:00
System.out.println("starting " + x + " + " + y);
2015-06-15 17:47:35 -07:00
pause(2000);
return x + y;
});
}
public void shutdown() { ex.shutdown(); }
public static void main(String[] args) {
ActiveObjectDemo d1 = new ActiveObjectDemo();
// Prevents ConcurrentModificationException:
List<Future<?>> results =
new CopyOnWriteArrayList<>();
for(float f = 0.0f; f < 1.0f; f += 0.2f)
results.add(d1.calculateFloat(f, f));
for(int i = 0; i < 5; i++)
results.add(d1.calculateInt(i, i));
2015-11-03 12:00:44 -08:00
System.out.println("All asynch calls made");
2015-06-15 17:47:35 -07:00
while(results.size() > 0) {
for(Future<?> f : results)
if(f.isDone()) {
try {
2015-11-03 12:00:44 -08:00
System.out.println(f.get());
2015-06-15 17:47:35 -07:00
} catch(InterruptedException |
ExecutionException e) {
throw new RuntimeException(e);
}
results.remove(f);
}
}
d1.shutdown();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
starting 0.0 + 0.0
All asynch calls made
0.0
starting 0.2 + 0.2
0.4
starting 0.4 + 0.4
0.8
2015-12-15 11:47:04 -08:00
starting 0.6 + 0.6
2015-06-15 17:47:35 -07:00
1.2
2015-12-15 11:47:04 -08:00
starting 0.8 + 0.8
2015-06-15 17:47:35 -07:00
1.6
2015-12-15 11:47:04 -08:00
starting 0 + 0
2015-06-15 17:47:35 -07:00
starting 1 + 1
0
2
2015-12-15 11:47:04 -08:00
starting 2 + 2
2015-06-15 17:47:35 -07:00
4
starting 3 + 3
6
starting 4 + 4
8
2015-09-07 11:44:36 -06:00
*/