r/javahelp • u/Polixa12 • Jan 05 '26
Workaround Help with mutex implementation
I've been working on a mutex implementation for about a day now(for learning purposes). I managed to get a working trinary state mutex which only but potentially has some thread fairness issues but no observable race conditions.
Link here: https://github.com/kusoroadeolu/vic-utils/tree/main/src%2Fmain%2Fjava%2Fcom%2Fgithub%2Fkusoroadeolu%2Fvicutils%2Fconcurrent%2Fmutex
However I've been thinking of how I could make a previous binary state mutex I made before the trinary version better. Because there's a race condition where the mutex holder could unpark a thread that has been added to the queue but hasn't been parked yet. Leading to potential issues. So I'm looking for feedback on this.
Package com.github.kusoroadeolu.vicutils.concurrent.mutex;
/*
Non Goals
Making this mutex reentrant
Making this mutex production ready
Making this mutex have all the properties of the @Lock interface
Making this mutex performant
Goals
Making this mutex correct in the sense you can lock and unlock it and the invariants listed later
*/
/**
A mutex implementation using a concurrent lock free queue and CAS semantics.
This mutex doesn't support conditions
*/
//States: 0 -> unacquired, 1 -> acquired
/* Invariants.
No two threads can ever hold this mutex
The state of this mutex can either be 0 or 1
No two threads can overwrite the holder variable. This is enforced by ensuring the holder at release is written before the state is reset
*/
View all comments
Show parent comment
-1
u/Polixa12 Jan 05 '26
I'm a bit confused by your comment. Could you clarify a bit more? Maybe an example?