Concurrency

More classes are defined in the java.util.concurrent.atomic and java.util.concurrent.locks packages. The java.util.concurrent.atomic package contains the following classes:

  • AtomicBoolean
  • AtomicInteger
  • AtomicIntegerArray
  • AtomicIntegerFieldUpdater (abstract)
  • AtomicLong
  • AtomicLongArray
  • AtomicLongFieldUpdater (abstract)
  • AtomicMarkableReference
  • AtomicReference
  • AtomicReferenceArray
  • AtomicReferenceFieldUpdater (abstract)
  • AtomicStampedReference

Most of these classes require little explanation as they simply define methods to update values atomically. For example, the AtomicInteger class defines the addAndGet() method, which adds a given value to the current value of the AtomicInteger object while returning the updated value. The abstract classes defined in this package are used internally but would very rarely be used directly in your applications' code.

In addition to the CountDownLatch, CyclicBarrier, and Semaphore classes from the java.util.concurrent package, more synchronization aids are defined in the java.util.concurrent.locks package:

  • AbstractOwnableSynchronizer (abstract, since API level 5)
  • AbstractQueuedLongSynchronizer (abstract, since API level 9)
  • AbstractQueuedLongSynchronizer (since API level 9)
  • AbstractQueuedSynchronizer (abstract)
  • AbstractQueuedSynchronizer.ConditionObject
  • LockSupport
  • ReentrantLock
  • ReentrantReadWriteLock
  • ReentrantReadWriteLock.ReadLock
  • ReentrantReadWriteLock.WriteLock

These classes are not commonly used in typical Android applications. Perhaps the most common one you would still use is the ReentrantReadWriteLock class, together with its ReentrantReadWriteLock.ReadLock and ReentrantReadWriteLock.WriteLock companions, as they allow for multiple reader threads to have access to the data (as long as there is no writer thread modifying the data) while there can only be one writer thread at a time. This is a common object when multiple threads access the same data for reading only, and you want to maximize throughput.

As a general rule, sharing data between threads creates problems (throughput, concurrency issues). Synchronization can become quite complex, and you need to have a solid understanding of the subject and of your code to enable shared data successfully. Debugging issues related to synchronization can also be quite an endeavor, so you should aim for simplicity before you try to optimize things like throughput. Focus on your application's quality first before any optimization.

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

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