Implementing an AtomicInteger
Contents
[NOTE] Updated April 6, 2020. This article may have outdated content or subject matter.
What is AtomicInteger
As the name suggests, AtomicInteger is an Integer with atomic operations. The difference between AtomicInteger and a regular Integer is that AtomicInteger uses a CAS method to make Integer’s increment and other operations atomic.
Knowledge needed before implementation
First, let’s look at the increment operation of AtomicInteger:
|
|
It uses a loop, and each time it loops, it gets the latest value, calculates the value after incrementing, uses compareAndSet to swap values, and checks the result. If it’s true, it returns the value after incrementing. If it’s false, it retries. This is a typical CAS operation.
And this compareAndSet operation is actually very simple, it just calls the compareAndSwapInt of the unsafe object
|
|
compareAndSwapInt performs the CAS modification operation based on the offset of the object where the member that needs the CAS operation is located.
Then let’s look at the get() method:
|
|
It just returns the value modified by volatile, because getting this value is an atomic action, and volatile can ensure that this value is the latest.
My implementation
It should be noted that Unsafe.getUnsafe
cannot be called directly, because it will determine whether it is a BootStap class loader or an Ext class loader. If not, it will throw an exception.
|
|
Sure, please provide the Markdown content you want to translate.
Author xiantang
LastMod 2020-04-06