repl.it
@tnobody/

non-blocking-vs-blocking.java

Java

Showing that you can turn async, non-blocking functions into pseudo blocking functions

fork
loading
Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.lang.*;
import java.util.concurrent.*;

class Main {

  static class Block {
    private boolean blocking = false;
    public void block() {
      blocking = true;
    }

    public void unBlock() {
      blocking = false;
    }

    public boolean isBlocking() {
      return blocking;
    }
  }

  private static void wait(Runnable then) {
    new Thread(() -> {
      try {
        Thread.sleep(1000);
      } catch(Exception e) {
        System.out.println("Your Thread has insomnia and cannot sleep");
      }
      
      then.run();
    }).start();
  }

  private static void waitSync() {
    Block block = new Block();
    block.block();
    wait(() -> block.unBlock());    
    while(block.isBlocking()) {  
      // This line is needed for java but can but ignored in this example
      try { Thread.sleep(250);} catch(Exception e) {}
    }
    System.out.println("Waited 1s sync");
  }

  public static void main(String[] args) {
    //System.out.println("Hello world!");
    boolean block;

    System.out.println("Before wait");
    wait(() -> System.out.println("Waited 1s async"));
    System.out.println("After wait");

    System.out.println("Before waitSync");
    waitSync();
    System.out.println("After waitSync");

  }
}