java - Construct a non-duplicate List collection, what's wrong with this code?
高洛峰
高洛峰 2017-06-12 09:25:37
0
2
1179

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
伊谢尔伦

Just use ConcurrentSkipListSetIt will be fine

漂亮男人

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template