private void Add(Node item)
{
/*
* this non-blocking / 'wait-free' linked list add was inspired by Apache
* Harmony's ConcurrentLinkedQueue Implementation.
*/
while (true)
{
Node currentTail = this.Tail;
Node tailNext = currentTail.Next;
if (Tail == currentTail)
{
if (tailNext != null)
{
/*
* we are in intermediate state here. the tails next pointer has been
* advanced but the tail itself might not be updated yet. help to
* advance the tail and try again updating it.
*/
Interlocked.CompareExchange(ref Tail, tailNext, currentTail); // can fail
}
else
{
/*
* we are in quiescent state and can try to insert the item to the
* current tail if we fail to insert we just retry the operation since
* somebody else has already added its item
*/
if (currentTail.CasNext(null, item))
{
/*
* now that we are done we need to advance the tail while another
* thread could have advanced it already so we can ignore the return
* type of this CAS call
*/
Interlocked.CompareExchange(ref Tail, item, currentTail);
return;
}
}
}
}
}