Map[Int, Lock]
where Lock
is just some synchronization mechanism like a Semaphore
.42
is made42
is made, triggering a new task (Task #2). This task should await the completion of the already-running task (Task #1) before startingThe crudest way to [associate a lock with an object] is to associate every key with the same lock, which results in the coarsest synchronization possible. On the other hand, you can associate every distinct key with a different lock, but this requires linear memory consumption and concurrency management for the system of locks itself, as new keys are discovered.Striped
allows the programmer to select a number of locks, which are distributed between keys based on their hash code. This allows the programmer to dynamically select a tradeoff between concurrency and memory consumption, while retaining the key invariant that ifkey1.equals(key2)
, thenstriped.get(key1) == striped.get(key2)
.
Size
"jobs" being executed all in parallel, with their keys being determined by id % 2
, i.e. all odd numbers share one lock, and even numbers share another. We should expect that only one odd-numbered id and one even-numbered id job should run at a time. You can change the implementation of getKey
to test other key collision scenarios.1024
"just seemed like the right thing to do" (there is a 1/1024
chance that a lock is shared between keys that didn't need to share one).