Created
February 24, 2021 22:25
-
-
Save wagyourtail/3b2fd304bfe4fd32914237aeeb6f5258 to your computer and use it in GitHub Desktop.
Graal concurrency test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package xyz.wagyourtail; | |
import org.graalvm.polyglot.Context; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.function.Function; | |
public class GraalTest { | |
static List<Thread> threads = new LinkedList<>(); | |
static Context ctx = Context.newBuilder("js").allowAllAccess(true).build(); | |
public static void main(String[] args) { | |
ctx.getBindings("js").putMember("test", new GraalTest()); | |
threads.add(Thread.currentThread()); | |
ctx.enter(); | |
ctx.eval("js", "console.log(test);" + | |
"test.addThread(() => {while (1) {console.log('t1'); test.tick(); }});" + | |
"test.addThread(() => {while (1) {console.log('t2'); test.tick(); }});"); | |
ctx.leave(); | |
runNextThreadOrTick(); | |
threads.remove(Thread.currentThread()); | |
} | |
public void addThread(Function<Object[], Object> fx) throws InterruptedException { | |
ctx.leave(); | |
Thread th; | |
threads.add(th = new Thread(() -> { | |
ctx.enter(); | |
fx.apply(new Object[0]); | |
ctx.leave(); | |
runNextThreadOrTick(); | |
threads.remove(Thread.currentThread()); | |
})); | |
synchronized (Thread.currentThread()) { | |
th.start(); | |
Thread.currentThread().wait(); | |
} | |
ctx.enter(); | |
} | |
public static void runNextThreadOrTick() { | |
int index = threads.indexOf(Thread.currentThread()); | |
if (index < threads.size() - 1) { | |
Thread next = threads.get(index + 1); | |
synchronized (next) { | |
next.notify(); | |
} | |
} else { | |
runTick(); | |
} | |
} | |
public void tick() throws InterruptedException { | |
ctx.leave(); | |
runNextThreadOrTick(); | |
synchronized (Thread.currentThread()) { | |
Thread.currentThread().wait(); | |
} | |
ctx.enter(); | |
} | |
public static void runTick() { | |
System.out.println("TICKED"); | |
if (threads.size() > 0) { | |
synchronized (threads.get(0)) { | |
threads.get(0).notify(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment