Wednesday, March 17, 2010

Atomically incremented counters

    private final static int startIndex = 1;
    private final static int pageSize = 5000;

    private AtomicInteger pageNo = new AtomicInteger(startIndex);

    private int getNextPage (){
        return pageNo.getAndIncrement();
    }

insteadOf**


    int pageNo = 0;

    private synchronized int getNextPage (){
        pageNo++;
        return pageNo;
    }



#####################################
#                                          More on it
#####################################



import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerUsage {
    private final static int startIndex = 1;
    private final static int pageSize = 5000;

    private AtomicInteger pageNo = new AtomicInteger(startIndex);
    private AtomicInteger anotherPageNo = new AtomicInteger(startIndex);

    private int getNextPage_getAndIncrement (){
        return pageNo.getAndIncrement();
    }
    private int getNextPage_incrementAndGet (){
        return anotherPageNo.incrementAndGet();
    }

    public AtomicIntegerUsage () {
    }

    public static void main (String[] args) {
        AtomicIntegerUsage t = new AtomicIntegerUsage ();
        System.out.println (" First page is page with getNextPage_getAndIncrement :"+t.getNextPage_getAndIncrement());
        System.out.println (" First page is page with getNextPage_incrementAndGet:"+t.getNextPage_incrementAndGet());
    }
}


 First page is page with getNextPage_getAndIncrement :1
 First page is page with getNextPage_incrementAndGet:2






No comments:

Post a Comment