Knowing About AtomicInteger

In some case, you will need variable which is need to be more reliable to count something on high speed process. If usually you use int to count something, now you need to consider about AtomicInteger. This class is under concurrent package so it can realiable for your multithread application process. This class even have wait() method 🙂

Simple example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.math.NumberUtils;

public class Main {
    public static void main(String[]args) throws IOException{  
        AtomicInteger i;
        String value;
        BufferedReader source = new BufferedReader(new InputStreamReader(System.in));
        try {            
            System.out.println("please input number: ");
            value = source.readLine();
            if(NumberUtils.isDigits(value)){
                i = new AtomicInteger(Integer.valueOf(value));
                System.out.println("this is value of i : " + i.get());
                System.out.println("this value using addAndGet(2) : " + i.addAndGet(2)); //add 2 then print
                System.out.println("this value after using incrementAndGet : " + i.incrementAndGet()); 
                System.out.println("this value after using decrementAndGet : " + i.decrementAndGet());
                System.out.println("this value after using getAndAdd(5) : " + i.getAndAdd(5)); // get then add 5
                System.out.println("current value : " + i.get());
            } else {
                System.out.println("wrong number");
            }            
        } catch (Exception e) {
            System.out.println(e);
        }
    }   
}

Result:

please input number: 
3
this is value of i : 3
this value using addAndGet(2) : 5
this value after using incrementAndGet : 6
this value after using decrementAndGet : 5
this value after using getAndAdd(5) : 5
current value : 10

For more documentation about this class, you can go to the site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s