A small toolkit of classes that support lock-free thread-safe programming on single records. In essence, the classes here provide provide an atomic conditional update operation of the form:
boolean compareAndSet(expectedValue, updateValue);
This method (which varies in argument types across different classes) atomically sets a record to the
updateValue if it currently holds the
true on success. Classes jere also contain methods to get and unconditionally set values.
The specifications of these methods enable to employ more efficient internal DB locking. CompareAndSwap operation is typically faster than using transactions, global lock or other concurrent protection.
Instances of classes Atomic.Boolean, Atomic.Integer, Atomic.Long, Atomic.String and Atomic.Var each provide access and updates to a single record of the corresponding type. Each class also provides appropriate utility methods for that type. For example, classes
Atomic.Integer provide atomic increment methods. One application is to generate unique keys for Maps:
Atomic.Long id = Atomic.getLong("mapId"); map.put(id.getAndIncrement(), "something");
Atomic classes are designed primarily as building blocks for implementing non-blocking data structures and related infrastructure classes. The
compareAndSet method is not a general replacement for locking. It applies only when critical updates for an object are confined to a
Atomic classes are not general purpose replacements for
java.lang.Integer and related classes. They do
compareTo. (Because atomic records are expected to be mutated, they are poor choices for hash table keys.) Additionally, classes are provided only for those types that are commonly useful in intended applications. Other types has to be wrapped into general Atomic.Var
You can also hold floats using
java.lang.Float#intBitsToFloat conversions, and doubles using
Atomically updated variable which may contain any type of record.