[concurrency-interest] A little lock free algorithm [the code]

studdugie studdugie at gmail.com
Thu Mar 30 21:12:31 EST 2006


public class TFailure
{
    volatile boolean dead;
    volatile long expiration =
        System.currentTimeMillis() + BACKOFF_INCREMENT;
    private static final long BACKOFF_MAX = ...;
    private static final long BACKOFF_INCREMENT = ...;
    private volatile long backoff = BACKOFF_INCREMENT;
    private final AtomicBoolean locked = new AtomicBoolean();

    /**
     * Increases the expiration timeout for the host if and only if
     * it's not already dead and the current expiration time has
      * elapsed.
     */
    void increment()
    {
        long millis;
        if( dead || (millis = System.currentTimeMillis()) < expiration )
            return;

        if( locked.compareAndSet( false, true ) )
        {
            backoff += BACKOFF_INCREMENT;
            if( backoff > BACKOFF_MAX )
                dead = true;
            else
                expiration = millis + backoff;
            locked.set( false );
        }
    }
}



More information about the Concurrency-interest mailing list