Author: saqibkhan

  • ScheduledExecutorService Interface

    A java.util.concurrent.ScheduledExecutorService interface is a subinterface of ExecutorService interface, and supports future and/or periodic execution of tasks.

    ScheduledExecutorService Methods

    Sr.No.Method & Description
    1<V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit)Creates and executes a ScheduledFuture that becomes enabled after the given delay.
    2ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)Creates and executes a one-shot action that becomes enabled after the given delay.
    3ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.
    4ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

    Example

    The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment.

    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.ScheduledFuture;
    import java.util.concurrent.TimeUnit;
    
    public class TestThread {
    
       public static void main(final String[] arguments) throws InterruptedException {
    
      final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
      final ScheduledFuture&lt;?&gt; beepHandler = 
         scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);
      scheduler.schedule(new Runnable() {
         @Override
         public void run() {
            beepHandler.cancel(true);
            scheduler.shutdown();			
         }
      }, 10, TimeUnit.SECONDS);
    } static class BeepTask implements Runnable {
      
      public void run() {
         System.out.println("beep");      
      }
    } }

    This will produce the following result.

    Output

    beep
    beep
    beep
    beep
    
  • ExecutorService Interface

    A java.util.concurrent.ExecutorService interface is a subinterface of Executor interface, and adds features to manage the lifecycle, both of the individual tasks and of the executor itself.

    ExecutorService Methods

    Sr.No.Method & Description
    1boolean awaitTermination(long timeout, TimeUnit unit)Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
    2<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)Executes the given tasks, returning a list of Futures holding their status and results when all complete.
    3<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.
    4<T> T invokeAny(Collection<? extends Callable<T>> tasks)Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do.
    5<T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.
    6boolean isShutdown()Returns true if this executor has been shut down.
    7boolean isTerminated()Returns true if all tasks have completed following shut down.
    8void shutdown()Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
    9List<Runnable> shutdownNow()Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
    10<T> Future<T> submit(Callable<T> task)Submits a value-returning task for execution and returns a Future representing the pending results of the task.
    11Future<?> submit(Runnable task)Submits a Runnable task for execution and returns a Future representing that task.
    12<T> Future<T> submit(Runnable task, T result)Submits a Runnable task for execution and returns a Future representing that task.

    Example

    The following TestThread program shows usage of ExecutorService interface in thread based environment.

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    
    public class TestThread {
    
       public static void main(final String[] arguments) throws InterruptedException {
    
      ExecutorService executor = Executors.newSingleThreadExecutor();
      try {
         executor.submit(new Task());
         System.out.println("Shutdown executor");
         executor.shutdown();
         executor.awaitTermination(5, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
         System.err.println("tasks interrupted");
      } finally {
         if (!executor.isTerminated()) {
            System.err.println("cancel non-finished tasks");
         }
         executor.shutdownNow();
         System.out.println("shutdown finished");
      }
    } static class Task implements Runnable {
      
      public void run() {
         
         try {
            Long duration = (long) (Math.random() * 20);
            System.out.println("Running Task!");
            TimeUnit.SECONDS.sleep(duration);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
    } }

    This will produce the following result.

    Output

    Shutdown executor
    Running Task!
    shutdown finished
    cancel non-finished tasks
    java.lang.InterruptedException: sleep interrupted
    	at java.lang.Thread.sleep(Native Method)
    	at java.lang.Thread.sleep(Thread.java:302)
    	at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:328)
    	at TestThread$Task.run(TestThread.java:39)
    	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    	at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    	at java.lang.Thread.run(Thread.java:662)
    
  • Executor Interface

    A java.util.concurrent.Executor interface is a simple interface to support launching new tasks.

    ExecutorService Methods

    Sr.No.Method & Description
    1void execute(Runnable command)Executes the given command at some time in the future.

    Example

    The following TestThread program shows usage of Executor interface in thread based environment.

    import java.util.concurrent.Executor;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    public class TestThread {
    
       public static void main(final String[] arguments) throws InterruptedException {
    
      Executor executor = Executors.newCachedThreadPool();
      executor.execute(new Task());
      ThreadPoolExecutor pool = (ThreadPoolExecutor)executor;
      pool.shutdown();
    } static class Task implements Runnable {
      
      public void run() {
         
         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task!");
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Task Completed");
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
    } }

    This will produce the following result.

    Output

    Running Task!
    Task Completed
    
  • AtomicReferenceArray Class

    A java.util.concurrent.atomic.AtomicReferenceArray class provides operations on underlying reference array that can be read and written atomically, and also contains advanced atomic operations. AtomicReferenceArray supports atomic operations on underlying reference array variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

    AtomicReferenceArray Methods

    Following is the list of important methods available in the AtomicReferenceArray class.

    Sr.No.Method & Description
    1public boolean compareAndSet(int i, E expect, E update)Atomically sets the element at position i to the given updated value if the current value == the expected value.
    2public E get(int i)Gets the current value at position i.
    3public E getAndSet(int i, E newValue)Atomically sets the element at position i to the given value and returns the old value.
    4public void lazySet(int i, E newValue)Eventually sets the element at position i to the given value.
    5public int length()Returns the length of the array.
    6public void set(int i, E newValue)Sets the element at position i to the given value.
    7public String toString()Returns the String representation of the current values of array.
    8public boolean weakCompareAndSet(int i, E expect, E update)Atomically sets the element at position i to the given updated value if the current value == the expected value.

    Example

    The following TestThread program shows usage of AtomicReferenceArray variable in thread based environment.

    import java.util.concurrent.atomic.AtomicReferenceArray;
    
    public class TestThread {
       private static String[] source = new String[10];
       private static AtomicReferenceArray<String> atomicReferenceArray 
    
      = new AtomicReferenceArray&lt;String&gt;(source);
    public static void main(final String[] arguments) throws InterruptedException {
      for (int i = 0; i&lt;atomicReferenceArray.length(); i++) {
         atomicReferenceArray.set(i, "item-2");
      }
      Thread t1 = new Thread(new Increment());
      Thread t2 = new Thread(new Compare());
      t1.start();
      t2.start();
      t1.join();
      t2.join();		
    } static class Increment implements Runnable {
      
      public void run() {
         
         for(int i = 0; i&lt;atomicReferenceArray.length(); i++) {
            String add = atomicReferenceArray.getAndSet(i,"item-"+ (i+1));
            System.out.println("Thread " + Thread.currentThread().getId() 
               + ", index " +i + ", value: "+ add);
         }
      }
    } static class Compare implements Runnable {
      
      public void run() {
         
         for(int i = 0; i&lt;atomicReferenceArray.length(); i++) {
            System.out.println("Thread " + Thread.currentThread().getId() 
               + ", index " +i + ", value: "+ atomicReferenceArray.get(i));
            boolean swapped = atomicReferenceArray.compareAndSet(i, "item-2", "updated-item-2");
            System.out.println("Item swapped: " + swapped);
            
            if(swapped) {
               System.out.println("Thread " + Thread.currentThread().getId() 
                  + ", index " +i + ", updated-item-2");
            }
         }
      }
    } }

    This will produce the following result.

    Output

    Thread 9, index 0, value: item-2
    Thread 10, index 0, value: item-1
    Item swapped: false
    Thread 10, index 1, value: item-2
    Item swapped: true
    Thread 9, index 1, value: updated-item-2
    Thread 10, index 1, updated-item-2
    Thread 10, index 2, value: item-3
    Item swapped: false
    Thread 10, index 3, value: item-2
    Item swapped: true
    Thread 10, index 3, updated-item-2
    Thread 10, index 4, value: item-2
    Item swapped: true
    Thread 10, index 4, updated-item-2
    Thread 10, index 5, value: item-2
    Item swapped: true
    Thread 10, index 5, updated-item-2
    Thread 10, index 6, value: item-2
    Thread 9, index 2, value: item-2
    Item swapped: true
    Thread 9, index 3, value: updated-item-2
    Thread 10, index 6, updated-item-2
    Thread 10, index 7, value: item-2
    Thread 9, index 4, value: updated-item-2
    Item swapped: true
    Thread 9, index 5, value: updated-item-2
    Thread 10, index 7, updated-item-2
    Thread 9, index 6, value: updated-item-2
    Thread 10, index 8, value: item-2
    Thread 9, index 7, value: updated-item-2
    Item swapped: true
    Thread 9, index 8, value: updated-item-2
    Thread 10, index 8, updated-item-2
    Thread 9, index 9, value: item-2
    Thread 10, index 9, value: item-10
    Item swapped: false
    
  • AtomicLongArray Class

    A java.util.concurrent.atomic.AtomicLongArray class provides operations on underlying long array that can be read and written atomically, and also contains advanced atomic operations. AtomicLongArray supports atomic operations on underlying long array variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

    AtomicLongArray Methods

    Following is the list of important methods available in the AtomicLongArray class.

    Sr.No.Method & Description
    1public long addAndGet(int i, long delta)Atomically adds the given value to the element at index i.
    2public boolean compareAndSet(int i, long expect, long update)Atomically sets the element at position i to the given updated value if the current value == the expected value.
    3public long decrementAndGet(int i)Atomically decrements by one the element at index i.
    4public long get(int i)Gets the current value at position i.
    5public long getAndAdd(int i, long delta)Atomically adds the given value to the element at index i.
    6public long getAndDecrement(int i)Atomically decrements by one the element at index i.
    7public long getAndIncrement(int i)Atomically increments by one the element at index i.
    8public long getAndSet(int i, long newValue)Atomically sets the element at position i to the given value and returns the old value.
    9public long incrementAndGet(int i)Atomically increments by one the element at index i.
    10public void lazySet(int i, long newValue)Eventually sets the element at position i to the given value.
    11public int length()Returns the length of the array.
    12public void set(int i, long newValue)Sets the element at position i to the given value.
    13public String toString()Returns the String representation of the current values of array.
    14public boolean weakCompareAndSet(int i, long expect, long update)Atomically sets the element at position i to the given updated value if the current value == the expected value.

    Example

    The following TestThread program shows usage of AtomicIntegerArray variable in thread based environment.

    import java.util.concurrent.atomic.AtomicLongArray;
    
    public class TestThread {
       private static AtomicLongArray atomicLongArray = new AtomicLongArray(10);
    
       public static void main(final String[] arguments) throws InterruptedException {
    
    
      for (int i = 0; i&lt;atomicLongArray.length(); i++) {
         atomicLongArray.set(i, 1);
      }
      Thread t1 = new Thread(new Increment());
      Thread t2 = new Thread(new Compare());
      t1.start();
      t2.start();
      t1.join();
      t2.join();
      System.out.println("Values: ");
      
      for (int i = 0; i&lt;atomicLongArray.length(); i++) {
         System.out.print(atomicLongArray.get(i) + " ");
      }
    } static class Increment implements Runnable {
      public void run() {
         for(int i = 0; i&lt;atomicLongArray.length(); i++) {
            long add = atomicLongArray.incrementAndGet(i);
            System.out.println("Thread " + Thread.currentThread().getId() 
               + ", index " +i + ", value: "+ add);
         }
      }
    } static class Compare implements Runnable {
      public void run() {
         for(int i = 0; i&lt;atomicLongArray.length(); i++) {
            boolean swapped = atomicLongArray.compareAndSet(i, 2, 3);
            
            if(swapped) {
               System.out.println("Thread " + Thread.currentThread().getId()
                  + ", index " +i + ", value: 3");
            }
         }
      }
    } }

    This will produce the following result.

    Output

    Thread 9, index 0, value: 2
    Thread 10, index 0, value: 3
    Thread 9, index 1, value: 2
    Thread 9, index 2, value: 2
    Thread 9, index 3, value: 2
    Thread 9, index 4, value: 2
    Thread 10, index 1, value: 3
    Thread 9, index 5, value: 2
    Thread 10, index 2, value: 3
    Thread 9, index 6, value: 2
    Thread 10, index 3, value: 3
    Thread 9, index 7, value: 2
    Thread 10, index 4, value: 3
    Thread 9, index 8, value: 2
    Thread 9, index 9, value: 2
    Thread 10, index 5, value: 3
    Thread 10, index 6, value: 3
    Thread 10, index 7, value: 3
    Thread 10, index 8, value: 3
    Thread 10, index 9, value: 3
    Values: 
    3 3 3 3 3 3 3 3 3 3
    
  • AtomicIntegerArray Class

    A java.util.concurrent.atomic.AtomicIntegerArray class provides operations on underlying int array that can be read and written atomically, and also contains advanced atomic operations. AtomicIntegerArray supports atomic operations on underlying int array variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

    AtomicIntegerArray Methods

    Following is the list of important methods available in the AtomicIntegerArray class.

    Sr.No.Method & Description
    1public int addAndGet(int i, int delta)Atomically adds the given value to the element at index i.
    2public boolean compareAndSet(int i, int expect, int update)Atomically sets the element at position i to the given updated value if the current value == the expected value.
    3public int decrementAndGet(int i)Atomically decrements by one the element at index i.
    4public int get(int i)Gets the current value at position i.
    5public int getAndAdd(int i, int delta)Atomically adds the given value to the element at index i.
    6public int getAndDecrement(int i)Atomically decrements by one the element at index i.
    7public int getAndIncrement(int i)Atomically increments by one the element at index i.
    8public int getAndSet(int i, int newValue)Atomically sets the element at position i to the given value and returns the old value.
    9public int incrementAndGet(int i)Atomically increments by one the element at index i.
    10public void lazySet(int i, int newValue)Eventually sets the element at position i to the given value.
    11public int length()Returns the length of the array.
    12public void set(int i, int newValue)Sets the element at position i to the given value.
    13public String toString()Returns the String representation of the current values of array.
    14public boolean weakCompareAndSet(int i, int expect, int update)Atomically sets the element at position i to the given updated value if the current value == the expected value.

    Example

    The following TestThread program shows usage of AtomicIntegerArray variable in thread based environment.

    import java.util.concurrent.atomic.AtomicIntegerArray;
    
    public class TestThread {
       private static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(10);
    
       public static void main(final String[] arguments) throws InterruptedException {
    
      
      for (int i = 0; i&lt;atomicIntegerArray.length(); i++) {
         atomicIntegerArray.set(i, 1);
      }
      Thread t1 = new Thread(new Increment());
      Thread t2 = new Thread(new Compare());
      t1.start();
      t2.start();
      t1.join();
      t2.join();
      System.out.println("Values: ");
      for (int i = 0; i&lt;atomicIntegerArray.length(); i++) {
         System.out.print(atomicIntegerArray.get(i) + " ");
      }
    } static class Increment implements Runnable {
      public void run() {
         for(int i = 0; i&lt;atomicIntegerArray.length(); i++) {
            int add = atomicIntegerArray.incrementAndGet(i);
            System.out.println("Thread " + Thread.currentThread().getId() 
               + ", index " +i + ", value: "+ add);
         }
      }
    } static class Compare implements Runnable {
      public void run() {
         for(int i = 0; i&lt;atomicIntegerArray.length(); i++) {
            boolean swapped = atomicIntegerArray.compareAndSet(i, 2, 3);
            
            if(swapped) {
               System.out.println("Thread " + Thread.currentThread().getId()
                  + ", index " +i + ", value: 3");
            }
         }
      }
    } }

    This will produce the following result.

    Output

    Thread 10, index 0, value: 2
    Thread 10, index 1, value: 2
    Thread 10, index 2, value: 2
    Thread 11, index 0, value: 3
    Thread 10, index 3, value: 2
    Thread 11, index 1, value: 3
    Thread 11, index 2, value: 3
    Thread 10, index 4, value: 2
    Thread 11, index 3, value: 3
    Thread 10, index 5, value: 2
    Thread 10, index 6, value: 2
    Thread 11, index 4, value: 3
    Thread 10, index 7, value: 2
    Thread 11, index 5, value: 3
    Thread 10, index 8, value: 2
    Thread 11, index 6, value: 3
    Thread 10, index 9, value: 2
    Thread 11, index 7, value: 3
    Thread 11, index 8, value: 3
    Thread 11, index 9, value: 3
    Values:
    3 3 3 3 3 3 3 3 3 3
    
  • AtomicReference Class

    A java.util.concurrent.atomic.AtomicReference class provides operations on underlying object reference that can be read and written atomically, and also contains advanced atomic operations. AtomicReference supports atomic operations on underlying object reference variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

    AtomicReference Methods

    Following is the list of important methods available in the AtomicReference class.

    Sr.No.Method & Description
    1public boolean compareAndSet(V expect, V update)Atomically sets the value to the given updated value if the current value == the expected value.
    2public boolean get()Returns the current value.
    3public boolean getAndSet(V newValue)Atomically sets to the given value and returns the previous value.
    4public void lazySet(V newValue)Eventually sets to the given value.
    5public void set(V newValue)Unconditionally sets to the given value.
    6public String toString()Returns the String representation of the current value.
    7public boolean weakCompareAndSet(V expect, V update)Atomically sets the value to the given updated value if the current value == the expected value.

    Example

    The following TestThread program shows usage of AtomicReference variable in thread based environment.

    import java.util.concurrent.atomic.AtomicReference;
    
    public class TestThread {
       private static String message = "hello";
       private static AtomicReference<String> atomicReference;
    
       public static void main(final String[] arguments) throws InterruptedException {
    
      atomicReference = new AtomicReference&lt;String&gt;(message);
      
      new Thread("Thread 1") {
         
         public void run() {
            atomicReference.compareAndSet(message, "Thread 1");
            message = message.concat("-Thread 1!");
         };
      }.start();
      System.out.println("Message is: " + message);
      System.out.println("Atomic Reference of Message is: " + atomicReference.get());
    } }

    This will produce the following result.

    Output

    Message is: hello
    Atomic Reference of Message is: Thread 1
    
  • AtomicBoolean Class

    A java.util.concurrent.atomic.AtomicBoolean class provides operations on underlying boolean value that can be read and written atomically, and also contains advanced atomic operations. AtomicBoolean supports atomic operations on underlying boolean variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

    AtomicBoolean Methods

    Following is the list of important methods available in the AtomicBoolean class.

    Sr.No.Method & Description
    1public boolean compareAndSet(boolean expect, boolean update)Atomically sets the value to the given updated value if the current value == the expected value.
    2public boolean get()Returns the current value.
    3public boolean getAndSet(boolean newValue)Atomically sets to the given value and returns the previous value.
    4public void lazySet(boolean newValue)Eventually sets to the given value.
    5public void set(boolean newValue)Unconditionally sets to the given value.
    6public String toString()Returns the String representation of the current value.
    7public boolean weakCompareAndSet(boolean expect, boolean update)Atomically sets the value to the given updated value if the current value == the expected value.

    Example

    The following TestThread program shows usage of AtomicBoolean variable in thread based environment.

    import java.util.concurrent.atomic.AtomicBoolean;
    
    public class TestThread {
    
       public static void main(final String[] arguments) throws InterruptedException {
    
      final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
      new Thread("Thread 1") {
         public void run() {
            while(true) {
               System.out.println(Thread.currentThread().getName() 
                  +" Waiting for Thread 2 to set Atomic variable to true. Current value is "
                  + atomicBoolean.get());
               if(atomicBoolean.compareAndSet(true, false)) {
                  System.out.println("Done!");
                  break;
               }
            }
         };
      }.start();
      new Thread("Thread 2") {
         public void run() {
            System.out.println(Thread.currentThread().getName() +
               ", Atomic Variable: " +atomicBoolean.get()); 
            System.out.println(Thread.currentThread().getName() +
               " is setting the variable to true ");
            atomicBoolean.set(true);
            System.out.println(Thread.currentThread().getName() +
               ", Atomic Variable: " +atomicBoolean.get()); 
         };
      }.start();
    } }

    This will produce the following result.

    Output

    Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
    Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
    Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
    Thread 2, Atomic Variable: false
    Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
    Thread 2 is setting the variable to true
    Thread 2, Atomic Variable: true
    Thread 1 Waiting for Thread 2 to set Atomic variable to true. Current value is false
    Done!
    
  • AtomicLong Class

    A java.util.concurrent.atomic.AtomicLong class provides operations on underlying long value that can be read and written atomically, and also contains advanced atomic operations. AtomicLong supports atomic operations on underlying long variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

    AtomicLong Methods

    Following is the list of important methods available in the AtomicLong class.

    Sr.No.Method & Description
    1public long addAndGet(long delta)Atomically adds the given value to the current value.
    2public boolean compareAndSet(long expect, long update)Atomically sets the value to the given updated value if the current value is same as the expected value.
    3public long decrementAndGet()Atomically decrements by one the current value.
    4public double doubleValue()Returns the value of the specified number as a double.
    5public float floatValue()Returns the value of the specified number as a float.
    6public long get()Gets the current value.
    7public long getAndAdd(long delta)Atomiclly adds the given value to the current value.
    8public long getAndDecrement()Atomically decrements by one the current value.
    9public long getAndIncrement()Atomically increments by one the current value.
    10public long getAndSet(long newValue)Atomically sets to the given value and returns the old value.
    11public long incrementAndGet()Atomically increments by one the current value.
    12public int intValue()Returns the value of the specified number as an int.
    13public void lazySet(long newValue)Eventually sets to the given value.
    14public long longValue()Returns the value of the specified number as a long.
    15public void set(long newValue)Sets to the given value.
    16public String toString()Returns the String representation of the current value.
    17public boolean weakCompareAndSet(long expect, long update)Atomically sets the value to the given updated value if the current value is same as the expected value.

    Example

    The following TestThread program shows a safe implementation of counter using AtomicLong in thread based environment.

    import java.util.concurrent.atomic.AtomicLong;
    
    public class TestThread {
    
       static class Counter {
    
      private AtomicLong c = new AtomicLong(0);
      public void increment() {
         c.getAndIncrement();
      }
      public long value() {
         return c.get();
      }
    } public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();
      
      //1000 threads
      for(int i = 0; i &lt; 1000 ; i++) {
         
         new Thread(new Runnable() {
            
            public void run() {
               counter.increment();
            }
         }).start();	
      }
      Thread.sleep(6000);			   		  
      System.out.println("Final number (should be 1000): " + counter.value());
    } }

    This will produce the following result.

    Output

    Final number (should be 1000): 1000
    
  • AtomicInteger Class

    A java.util.concurrent.atomic.AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features.

    AtomicInteger Methods

    Following is the list of important methods available in the AtomicInteger class.

    Sr.No.Method & Description
    1public int addAndGet(int delta)Atomically adds the given value to the current value.
    2public boolean compareAndSet(int expect, int update)Atomically sets the value to the given updated value if the current value is same as the expected value.
    3public int decrementAndGet()Atomically decrements by one the current value.
    4public double doubleValue()Returns the value of the specified number as a double.
    5public float floatValue()Returns the value of the specified number as a float.
    6public int get()Gets the current value.
    7public int getAndAdd(int delta)Atomiclly adds the given value to the current value.
    8public int getAndDecrement()Atomically decrements by one the current value.
    9public int getAndIncrement()Atomically increments by one the current value.
    10public int getAndSet(int newValue)Atomically sets to the given value and returns the old value.
    11public int incrementAndGet()Atomically increments by one the current value.
    12public int intValue()Returns the value of the specified number as an int.
    13public void lazySet(int newValue)Eventually sets to the given value.
    14public long longValue()Returns the value of the specified number as a long.
    15public void set(int newValue)Sets to the given value.
    16public String toString()Returns the String representation of the current value.
    17public boolean weakCompareAndSet(int expect, int update)Atomically sets the value to the given updated value if the current value is same as the expected value.

    Example

    The following TestThread program shows a unsafe implementation of counter in thread based environment.

    public class TestThread {
    
       static class Counter {
    
      private int c = 0;
      public void increment() {
         c++;
      }
      public int value() {
         return c;
      }
    } public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();
      
      //1000 threads
      for(int i = 0; i &lt; 1000 ; i++) {
         
         new Thread(new Runnable() {
            
            public void run() {
               counter.increment();
            }
         }).start(); 
      }  
      Thread.sleep(6000);
      System.out.println("Final number (should be 1000): " + counter.value());
    } }

    This may produce the following result depending upon computer’s speed and thread interleaving.

    Output

    Final number (should be 1000): 1000
    

    Example

    The following TestThread program shows a safe implementation of counter using AtomicInteger in thread based environment.

    import java.util.concurrent.atomic.AtomicInteger;
    
    public class TestThread {
    
       static class Counter {
    
      private AtomicInteger c = new AtomicInteger(0);
      public void increment() {
         c.getAndIncrement();
      }
      public int value() {
         return c.get();
      }
    } public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();
      
      //1000 threads
      for(int i = 0; i &lt; 1000 ; i++) {
         new Thread(new Runnable() {
            public void run() {
               counter.increment();
            }
         }).start(); 
      }  
      Thread.sleep(6000);
      System.out.println("Final number (should be 1000): " + counter.value());
    } }

    This will produce the following result.

    Output

    Final number (should be 1000): 1000