title: a generic lock-free synchronization
body: <p>The implementation of lock-free data structures is sometimes not easy to implement. The following approach may seem generic and easy but I think here we have some issues:</p>
  
  <pre><code>private AtomicBoolean lock = new AtomicBoolean(false);
  
      public void func(...) {
          while !lock.compareAndSet(false,true);
          // Some code goes here...
          ...
          ...
          ...
          lock.set(false); 
      }
  }
  </code></pre>
  
  <p>I think The code above is not really "lock-free", as it locks the awaiting Threads in the while loop in busy-wait mode.</p>
  
  <p>Therefore, the code is suitable only when the "right" lock-free synchronization is impossible.</p>
  
  <p>My question is - Is it possible to implement a generic lock-free with some different approach and it will works so threads will not be in blocked(like synchronized) or busy mode state and the code will run parallel, so we improve performance?</p>
  
  <p>My aim is to keep the threads running. I know that if the code is long, it is better to use the synchronized mechanism instead of the lock-free implementation, so let's assume we are talking on short code.</p>
  
  <p>For example, below is example of Linkedlist which I think is good approach but it not generic for common data stractures. 
  if we are used here with AtomicBoolean as I show above, it will not be realy "lock-free".</p>
  
  <pre><code>public class LinkedList&lt;T&gt; {
  
      private AtomicReference&lt;Link&lt;T&gt;&gt; head = new AtomicReference(null);
  
      public  void add(T data) {
        Link&lt;T&gt; localHead;
        Link&lt;T&gt; newHead = new Link&lt;&gt;(null, data);
  
        do {
          localHead = head.get();
          newHead.next = localHead;        
        } while (!head.compareAndSet(localHead, newHead));
      }
  }
  </code></pre>