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

David Holmes dcholmes at optusnet.com.au
Thu Mar 30 21:28:58 EST 2006


Okay this is basically a tryLock style of approach: if you can't get the
lock you know someone else is doing the increment. You've built your own
tryLock out of an AtomicBoolean.

If backoff is only read and written when you've set the atomic boolean then
you can drop the volatile for it as it "piggybacks" on the AtomicBoolean
memory semantics.

Cheers,
David Holmes

> -----Original Message-----
> From: concurrency-interest-bounces at cs.oswego.edu
> [mailto:concurrency-interest-bounces at cs.oswego.edu]On Behalf Of
> studdugie
> Sent: Friday, 31 March 2006 12:13 PM
> To: concurrency-interest at cs.oswego.edu
> Subject: [concurrency-interest] A little lock free algorithm [the code]
>
>
> 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 );
>         }
>     }
> }
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest



More information about the Concurrency-interest mailing list