In this thread concurrency tutorial we will learn what is AtomicLong in java with program and examples. We will learn important methods of AtomicLong like getAndSet, compareAndSet, incrementAndGet, getAndAdd, getAndIncrement, decrementAndGet, getAndDecrement and how to use them in thread concurrency in java.
Contents of page :
- 1) What is java.util.concurrent.atomic.AtomicLong in java ?
- 1.1) AtomicLong constructors in java >
- AtomicLong()
- AtomicLong(long initialValue)
- 1.2) AtomicLong important Methods in java >
- long get()
- void set(long newValue)
- long getAndSet(long newValue)
- boolean compareAndSet(long expect, long update)
- 1.3) Addition methods in java >
- long addAndGet(long value)
- long incrementAndGet()
- long getAndAdd(long value)
- long getAndIncrement()
- 1.4) Subtraction methods in java >
- long decrementAndGet()
- long getAndDecrement()
- 2) Example/Program to demonstrate usage of AtomicLong in java >
- Occasionally output may be different in java >
- 3) Program to show Consequences of using Long in place of AtomicLong in java >
1) What is java.util.concurrent.atomic.AtomicLong in java?
java.util.concurrent.AtomicLong provides you with long value that is updated atomically. i.e. we can use these classes without any explicit synchronization in multithreading environment, because any operation done on these classes is thread safe.
In next post we will learn Implementation of custom/own AtomicLong in java
1.1) AtomicLong constructors in java >
- AtomicLong()
Creates a new AtomicLong and is initialized to 0.
Example >
AtomicLong atomicLong =new AtomicLong();
|
We have created a new AtomicLong and it is initialized to 0.
- AtomicLong(long initialValue)
Creates a new AtomicLong and is initialized to specified initialValue.
Example >
AtomicLong atomicLong =new AtomicLong(11);
|
We have created a new AtomicLong and it is initialized to 11.
1.2) AtomicLong important Methods in java >
- long get()
method returns the current value
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.get();
|
Method will return 11.
- void set(long newValue)
Sets to newValue.
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.set(12);
|
Method will set return AtomicLong to 12.
- long getAndSet(long newValue)
Sets to newValue and returns the old value.
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.getAndSet(12);
|
Method will set return AtomicLong to 12. And return 11.
- boolean compareAndSet(long expect, long update)
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.compareAndSet(11, 12);
|
Now, in call to compareAndSet method first parameter [i.e. 11] is equal to original value, so method will set AtomicLong to 12.
And returns true if value was successfully set.
1.3) Addition methods in java >
- long addAndGet(long value)
adds value to the current value. And return updated value.
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.addAndGet(4);
|
adds 4 to the current value. And return 15.
- long incrementAndGet()
increments current value by 1. And return updated value.
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.incrementAndGet();
|
increments current value by 1. And return 12.
- long getAndAdd(long value)
Method return current value. And adds value to the current value.
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.getAndAdd(4);
|
Method return 11. And adds 4 to 11.
- long getAndIncrement()
Method return current value. And increments current value by 1.
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.getAndIncrement();
|
Method return 11. And increments 11 by 1.
1.4) Subtraction methods in java >
- long decrementAndGet()
decrements current value by 1. And return updated value.
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.decrementAndGet();
|
decrements current value by 1. And return 10.
- long getAndDecrement()
Method return current value. And decrements current value by 1.
Example >
AtomicLong atomicLong =new AtomicLong(11);
atomicLong.getAndDecrement();
|
Method return 11. And decrements 11 by 1.
2) Example/Program to demonstrate usage of AtomicLong in java >
package AtomicLong;
import java.util.concurrent.atomic.AtomicLong;
class MyRunnable implements Runnable{
public void run(){
for(int i=0;i<2;i++){
System.out.println("ThreadName="+Thread.currentThread().getName()
+" > "+
AtomicLongTest.sharedAtomicLong.incrementAndGet());
}
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
/**
* Main class
*/
public class AtomicLongTest {
//Create a new AtomicLong and is initialized to 0.
static AtomicLong sharedAtomicLong =new AtomicLong();
public static void main(String...args) throws InterruptedException{
MyRunnable runnable=new MyRunnable();
Thread thread1=new Thread(runnable,"Thread-1");
Thread thread2=new Thread(runnable,"Thread-2");
thread1.start();
thread2.start();
Thread.sleep(1000); //delay to ensure Thread-1 and Thread-2 finish
System.out.println("After completion of both threads, "
+ "sharedAtomicLong = "+sharedAtomicLong);
}
}
/*OUTPUT
ThreadName=Thread-1 > 1
ThreadName=Thread-2 > 2
ThreadName=Thread-1 > 3
ThreadName=Thread-2 > 4
After completion of both threads, sharedAtomicLong = 4
*/
|
In the program, a static AtomicLong is created with name sharedAtomicLong and is initialized to 0. Then, Thread-1 and Thread-2 atomically increments sharedAtomicLong inside run( ) method using incrementAndGet() method [incrementAndGet() method increments current value by 1. And return updated value].
Here, sharedAtomicLong being AtomicLong prevents two threads from writing to it at the same time.
Occasionally output may be different in java >
/*OUTPUT
ThreadName=Thread-2 > 1
ThreadName=Thread-2 > 3
ThreadName=Thread-1 > 2
ThreadName=Thread-1 > 4
After completion of both threads, sharedAtomicLong = 4
*/
sharedAtomicLong is incremented atomically, but sysout statements have executed out of order.
3) Program to show Consequences of using Long in place of AtomicLong in java >
class MyRunnable implements Runnable{
public void run(){
for(int i=0;i<2;i++){
System.out.println("ThreadName="+Thread.currentThread().getName()
+" > "+
++AtomicLongTest.sharedLong);
}
}
}
/**
* Main class
*/
public class AtomicLongTest {
//Create a new Long and initialize with 0.
static Long sharedLong =new Long(0);
public static void main(String...args) throws InterruptedException{
MyRunnable runnable=new MyRunnable();
Thread thread1=new Thread(runnable,"Thread-1");
Thread thread2=new Thread(runnable,"Thread-2");
thread1.start();
thread2.start();
Thread.sleep(1000); //delay to ensure Thread-1 and Thread-2 finish
System.out.println("After completion of both threads, "
+ "sharedLong = "+sharedLong);
}
}
/*OUTPUT
ThreadName=Thread-1 > 1
ThreadName=Thread-2 > 1
ThreadName=Thread-1 > 2
ThreadName=Thread-2 > 3
After completion of both threads, sharedLong = 3
*/
|
Long class is not thread safe so two threads updated sharedLong out of order.
So at end of program sharedLong’s value was 3, whereas it should have been 4 because sharedLong was initialized to 0 and was incremented 4 times in java.
In this thread concurrency tutorial we learned what is AtomicLong in java with program and examples. We learned important methods of AtomicLong like getAndSet, compareAndSet, incrementAndGet, getAndAdd, getAndIncrement, decrementAndGet, getAndDecrement and how to use them in thread concurrency in java.
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>
Atomic operations >
Atomic operations in java
AtomicInteger in java
Implementation of custom/own AtomicInteger in java
AtomicLong in java
Implementation of custom/own AtomicLong in java
AtomicBoolean in java
Lock and Reentrant Locks >
Locks and ReEntrantLocks in java
Implementation of custom/own Lock and ReEntrantLock in java
ReentrantLock class provides implementation of Lock’s newCondition() method - description and solving producer consumer program using this method
ReadWriteLock and ReentrantReadWriteLock >
ReadWriteLock and ReentrantReadWriteLock in java
Implementation of custom/own ReadWriteLock and ReentrantReadWriteLock in java
Thread concurrency Interviews >