Day 3/7 of Java Concurrency -
Compare and set - the secret sauce behind lock free data structures
Lock free data structures manage to avoid race conditions without using any locks at all - how is this even possible?
Enter compareAndSet, a method exposed by AtomicReference.
The API is very straightforward -
ref.compareAndSet(expected, newValue) -> if the current value is expected, then it sets it to newValue, otherwise if another thread updated it - we get a return false.
No waiting, no blocking.
The key pattern that makes this useful is running it in a loop, we keep comparing and setting in a loop till the thread eventually gets one return true, and we exit!
Look at this lock free implementation of a stack that can handle concurrent reads and writes!
Day 2/7 of Java Concurrency - Semaphores
We all know about locks for mutual exclusion. But what if we want to allow N threads in at once?
Semaphores solve this exact problem - the api is quite simple - you initialize with a number of "permits"
Semaphore semaphore = new Semaphore(n, true);
The key methods -
acquire() - takes a permit (blocks if none available) release() - returns a permit
the boolean parameter is for fairness -
true = fair (FIFO)
false = no fairness guarentee (but faster!)
Any thread can release a permit. Unlike a lock, the thread that acquires doesn't have to be the one that releases - allowing signaling between threads.