Hacker News new | ask | show | jobs
by kodablah 2803 days ago
Nice, was just reading your issue [0]. I spent a bit of time the other day thinking how I could implement these thread ops on the JVM (JVM rambling henceforth, skip if not curious)...

First, my project's output requires no runtime/dependencies, so I am restricted to JVM libs only. Memory is implemented as a ByteBuffer which does not have atomic access. I didn't quite understand the threads spec wrt data init on mem so I'll have to get clarification there (lock all mem? just go and pray?). The implementation will create four synthetic methods in the class: lock, unlock, wait, and wake. The class will have a field that is ConcurrentMap<Integer, int[]> where the key is the mem offset being locked, and the value is an array of mutable int refs size 2, the first being lock ref count and the second being wait ref count. Imports of shared memory pass that around along w/ the ByteBuffer.

Lock will create/incr ref count and secure the lock via monitorenter on the int array (or fail if ref > 0 when just a try). Unlock will monitorexit and decr the count (removing from map if both ref counts are 0). All ops are done between this lock/unlock. Wait/wake is via wait/notify on the JVM, but JVM has no construct to say how many or if any threads were woken up on notify, so I have to keep the wait count. Incr/decr on the ref and wait vs notify (in a loop if > 1) is done as expected using wait() and notify() on the array itself. The lock, unlock, wait, and notify are done w/in concurrent map's compute making them atomic. Lock/wait lazily create the refs in the map. Unlock/notify, upon reaching 0 for both refs at the end, clear the refs out of the map.

I have looked into existing JVM constructs and this seems to be the best way (I wish I could use Guava's Striped or the like, but I have no dependency/runtime requirement on outputted class files). Countdown latches, other locks, conditions, etc were all runtime overkill. I could have better performance than a boxed-int map with some extra code but wanted to keep it simple. Granted this is all pie-in-the-sky thinking, the impl will change it for sure.

I am afraid to start an implementation because the proposal isn't further along yet (I really need some test cases in the suite to make me feel better).

0 - https://github.com/WebAssembly/threads/issues/106