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<E> implements Stack<E>{    @SuppressWarnings(hiding)    private class Node<E>{        public E item;        public Node<E> next;        public Node(E item){            this.item=item;        }    }    @SuppressWarnings(rawtypes)    private AtomicReference<Node> head;    @SuppressWarnings(rawtypes)    ConcurrentStack(){        head = new AtomicReference<Node>();    }    @SuppressWarnings(unchecked)    @Override    public void push(E item) {        Node<E> newHead = new Node<E>(item);        Node<E> headNode = null;        do        {            headNode = head.get();            newHead.next = headNode;        }while(!head.compareAndSet(headNode, newHead));    }    @SuppressWarnings(unchecked)    @Override    public E pop() {        Node<E> 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<E> 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<E> node=head.get();node != null; node=node.next){            size++;        }        return size;    }}
Custom concurrent stack implementation in Java
java;multithreading;stack