java non blocking notifier

Solutions on MaxInterview for java non blocking notifier by the best coders in the world

showing results for - "java non blocking notifier"
Gabriela
29 Mar 2016
1import java.util.concurrent.CompletableFuture;
2import java.util.concurrent.ThreadLocalRandom;
3import java.util.concurrent.TimeUnit;
4
5public class GetTaskNotificationWithoutBlocking {
6
7  public static void main(String... argv) throws Exception {
8    ExampleService svc = new ExampleService();
9    GetTaskNotificationWithoutBlocking listener = new GetTaskNotificationWithoutBlocking();
10    CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work);
11    f.thenAccept(listener::notify);
12    System.out.println("Exiting main()");
13  }
14
15  void notify(String msg) {
16    System.out.println("Received message: " + msg);
17  }
18
19}
20
21class ExampleService {
22
23  String work() {
24    sleep(7000, TimeUnit.MILLISECONDS); /* Pretend to be busy... */
25    char[] str = new char[5];
26    ThreadLocalRandom current = ThreadLocalRandom.current();
27    for (int idx = 0; idx < str.length; ++idx)
28      str[idx] = (char) ('A' + current.nextInt(26));
29    String msg = new String(str);
30    System.out.println("Generated message: " + msg);
31    return msg;
32  }
33
34  public static void sleep(long average, TimeUnit unit) {
35    String name = Thread.currentThread().getName();
36    long timeout = Math.min(exponential(average), Math.multiplyExact(10, average));
37    System.out.printf("%s sleeping %d %s...%n", name, timeout, unit);
38    try {
39      unit.sleep(timeout);
40      System.out.println(name + " awoke.");
41    } catch (InterruptedException abort) {
42      Thread.currentThread().interrupt();
43      System.out.println(name + " interrupted.");
44    }
45  }
46
47  public static long exponential(long avg) {
48    return (long) (avg * -Math.log(1 - ThreadLocalRandom.current().nextDouble()));
49  }
50
51}