Okay, implementing the Java pendant for the goroutine example in
http://golang.org/doc/effective_go.html#goroutines here we go using JDK8:
public interface AsyncUtils {
default public void async(Runnable runnable) {
Dispatch.getGlobalQueue().execute(runnable);
}
default public void asyncAfter(long duration, TimeUnit unit, Runnable runnable) {
Dispatch.getGlobalQueue().executeAfter(duration, unit, runnable);
}
}
public class GoroutineTest implements AsyncUtils {
private static Random Rand = new Random(System.currentTimeMillis());
@After
public void tearDown() throws InterruptedException
{
DispatcherConfig.getDefaultDispatcher().shutdown();
}
@Test
public void asyncSort() throws InterruptedException
{
BlockingQueue<Integer> channel = new LinkedBlockingQueue<>();
List<Integer> list = new ArrayList<>();
for(int i = 0; i < 100; i++) {
list.add(Rand.nextInt());
}
async(()-> {
Collections.sort(list);
channel.add(1);
});
int result = doSomethingForAWhile();
int value = channel.take();
Assert.assertEquals(1, value);
Assert.assertTrue(result != -1);
}
private int doSomethingForAWhile() {
int result = -1;
while(!(Rand.nextInt(20) == 5) || result == -1) {
result = Rand.nextInt();
}
return result;
}
}
That was easy ... :-).