Using atomic arrays

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:

  1. You get the value of the variable, which is the old value of the variable.
  2. You change the value of the variable in a temporal variable, which is the new value of the variable.
  3. You substitute the old value with the new value if the old value is equal to the actual value of the variable. The old value may be different from the actual value if another thread has changed it.

With this mechanism, you don't need to use a synchronization mechanism, so you avoid deadlocks and you obtain better performance. This mechanism also has its drawbacks. Operations must be free from any side effects as they might be retried using livelocks with highly contended resources; they are also harder to monitor for performance when compared with standard locks.

Java implements this mechanism in atomic variables. These variables provide the compareAndSet() method, which is an implementation of the compare-and-swap operation and other methods based on it.

Java also introduced atomic arrays that provide atomic operations for arrays of integer or long numbers. In this recipe, you will learn how to use the AtomicIntegerArray class to work with atomic arrays. Take into account that if you use AtomicInteger[], it's not a thread-safe object. The individual AtomicInteger objects are thread-safe, but the array as a data structure is not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.151.107