Search code examples
scalaconcurrencyfunctional-programmingscala-cats

MVar fairness guarantees?


I'm building a thread-safe shared state with MVar and due to requirements I need some fairness guarantees (If two threads asked a state under MVar one after the other then as soon as the state is available the threads will take it in the order they asked for it).

I didn't find any note in the MVar documentation.

So in case of fairness guarantees is it required to build some sort of a wrapper of ReentrantLock(true) fair lock?


Solution

  • I don't know what the exact guarantees are, but in cats effect, fairness is frequently mentioned in terms of the scheduler. That means you may not be able to get the exact ordering you mentioned on the first acquisition of an MVar, but no one should be getting starved, because after your turn you yield your fiber and have to be rescheduled before acquiring the MVar again.

    In other words, if you need exact ordering or exact round robin, you're going to have to implement that yourself, but if your requirements are really something like "every eligible fiber gets roughly the same amount of runtime without getting starved" then you get that almost for free.