Consider that you need to implement a concurrent application that has one or more objects shared by several threads. In such a scenario, you have to protect access to their attributes using a synchronization mechanism, such as locks or the synchronized keyword, to avoid data inconsistency errors.
These mechanisms have the following problems:
- Deadlock: This situation occurs when a thread is blocked waiting for a lock that is locked by other threads that will never free it. This situation blocks the program, so it will never finish.
- If only one thread is accessing the shared object, it has to execute the code necessary to get and release the lock.
To provide better performance in this situation, the compare-and-swap operation was developed. This operation implements the modification of the value of a variable in the following three steps:
- You get the value of the variable, which is the old value...