Custom concurrent stack implementation in Java I don't want to use synchronized for sizeof method, any suggestion to implement the method thread safe?

package com.r.collection.adt;

import java.util.concurrent.atomic.AtomicReference;


public class ConcurrentStack&lt;E&gt; implements Stack&lt;E&gt;{

    @SuppressWarnings("hiding")
    private class Node&lt;E&gt;{

        public E item;
        public Node&lt;E&gt; next;

        public Node(E item){
            this.item=item;
        }

    }

    @SuppressWarnings("rawtypes")
    private AtomicReference&lt;Node&gt; head;

    @SuppressWarnings("rawtypes")
    ConcurrentStack(){
        head = new AtomicReference&lt;Node&gt;();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void push(E item) {
        Node&lt;E&gt; newHead = new Node&lt;E&gt;(item);
        Node&lt;E&gt; headNode = null;
        do
        {
            headNode = head.get();
            newHead.next = headNode;
        }while(!head.compareAndSet(headNode, newHead));

    }


    @SuppressWarnings("unchecked")
    @Override
    public E pop() {
        Node&lt;E&gt; headNode = head.get();
        do
        {
            headNode = head.get();
            if(headNode == null)
                return null;
        }while(!head.compareAndSet(headNode, headNode.next));

        return headNode.item;
    }

    @SuppressWarnings("unchecked")
    @Override
    public E peek() {
        Node&lt;E&gt; headNode = head.get();
        if(headNode == null){
            return null;
        }

        return headNode.item;
    }

    @Override
    public boolean isEmpty() {

        return head.get() == null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public synchronized int  sizeOf() {
        int size=0;
        for(Node&lt;E&gt; node=head.get();node != null; node=node.next){
            size++;
        }
        return size;
    }

}
The synchronization you are currently using is not even working the way you intend to: as nothing else is synchronizing on this (like the sizeOf() method) you might as well not make the method synchronized.

You could stick a size field into your Node which gets set on inserting, something along the lines of this:

do {
    headNode = head.get();
    newHead.next = headNode;
    newHead.size = (headNode == null) ? 1 : headNode.size + 1;
} while (!head.compareAndSet(headNode, newHead));


This should allow reduction of the sizeOf() method to:

public int sizeOf() {
    return head.get().size;
}