Is LinkedList thread-safe when I'm accessing it with offer and poll exclusively?

后端 未结 4 1824
长情又很酷
长情又很酷 2020-12-09 03:07

I have a linked list samples:

protected LinkedList samples = new LinkedList();

I\'m append

相关标签:
4条回答
  • 2020-12-09 03:28

    if you have a JDK, you can look at the source code of "Collections.synchronizedList()". It is simple, so you can create a copy of this method specialized to get both LinkedList and synchronization functionnalities.

    public class SynchronizedLinkedList<T> implements List<T> {
    
        private LinkedList<T> list;
    
        private Object lock;
    
        public void add(T object) {
            synchronized(lock) {
                list.add(object);
            }
        }
    
        // etc.
    }
    
    0 讨论(0)
  • 2020-12-09 03:30

    No LinkedList is not thread safe. Use LinkedBlockingDeque instead

    0 讨论(0)
  • 2020-12-09 03:32

    That is correct - LinkedList is not synchronized and thus not thread safe. If you do not want to use the newer synchronized analogies of LinkedList, namely, ConcurrentLinkedQueue or LinkedBlockingQueue, you can initialize LinkedList like this:

    LinkedList<RawDataset> samples = (LinkedList)Collections.synchronizedList(new LinkedList<RawDataset>());
    
    0 讨论(0)
  • 2020-12-09 03:36

    LinkedList is not thread safe. You'd have to do the locking yourself.

    Try ConcurrentLinkedQueue or LinkedBlockingDeque instead if it fits your needs, they are thread safe but slightly different behavior than LinkedList.

    0 讨论(0)
提交回复
热议问题