| Start | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Creating Atomic Types For simple multi-threaded code, using synchronization (opens new window) is acceptable. However, using synchronization does have a liveness impact, and as a codebase becomes more complex, the likelihood goes up that you will end up with Deadlock (opens new window), Starvation, or Livelock (opens new window). In cases of more complex concurrency, using Atomic Variables is often a better alternative, as it allows an individual variable to be accessed in a thread-safe manner without the overhead of using synchronized methods or code blocks. Creating an Similarly for other instance types. Similarly for other atomic types. There is a notable exception that there is no If you are willing to use |
||||||||||||
| Motivation for Atomic Types The simple way to implement multi-threaded applications is to use Java's built-in synchronization and locking primitives; e.g. the This implementation will work correctly. However, if you have a large number of threads making lots of simultaneous calls on the same
If one thread attempts to acquire the lock while another one holds it, the attempting thread will be blocked (stopped) at step 1 until the lock is released. If multiple threads are waiting, one of them will get it, and the others will continue to be blocked. This can lead to a couple of problems: How does one implement Atomic Types?Let us start by rewriting the example above using We have replaced the But the most important thing is that we can remove the Furthermore, while two threads might actually attempt to update the same How do Atomic Types work?Atomic types typically rely on specialized hardware instructions in the instruction set of the target machine. For example, Intel-based instruction sets provide a These low-level instructions are are used to implement higher-level operations in the APIs of the respective Parameters
RemarksMany on essentially combinations of volatile reads or writes and CAS (opens new window) operations. Best way to understand this is to look at the source code directly. E.g. AtomicInteger (opens new window), Unsafe.getAndSet (opens new window) |
Read Article
https://develop.horje.com/learn/1434/reference