package org.maachang.jni.io ;

import java.util.concurrent.atomic.AtomicLong;

/**
 * シーケンスID発行.
 * 
 * @version 2010/06/04
 * @author  masahito suzuki
 * @since   SeabassNativeIO-1.0.0
 */
class AtomicSeq {
    private final AtomicLong ato = new AtomicLong( 0 ) ;
    private long max = 0 ;
    public AtomicSeq() {
        this(-1L);
    }
    public AtomicSeq( long n ) {
        if( n <= 0L ) {
            n = Long.MAX_VALUE ;
        }
        max = n ;
    }
    public long get() {
        long n ;
        long r ;
        while( true ) {
            n = ato.get() ;
            r = n + 1L ;
            if( r >= max ) { r = 0L; }
            if( ato.compareAndSet( n,r ) ) {
                return r ;
            }
        }
    }
    public long max() {
        return max ;
    }
}
