search

Home  >  Q&A  >  body text

java - Construct a non-duplicate List collection, what's wrong with this code?

The function we hope to achieve is to provide an atomic operation for List: if not, add it. Because ArrayList itself is not thread-safe, it is converted into a thread-safe class through the collection Collections.synchronizedList, and then through an auxiliary method to ListAchieve such a function.

class BadListHelper <E> {  
    public List<E> list = Collections.synchronizedList(new ArrayList<E>());  

    public synchronized boolean putIfAbsent(E x) {  
        boolean absent = !list.contains(x);  
        if (absent)  
            list.add(x);  
        return absent;  
    }  
}  
 

Is this code thread-unsafe? If so, can you prove it? Thanks

高洛峰高洛峰2723 days ago1124

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-06-12 09:27:37

    Just use ConcurrentSkipListSetIt will be fine

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-12 09:27:37

    A non-repeating List is just a Set, right? , requires atoms, isn't it a thread-safe Set?

    reply
    0
  • Cancelreply