Home > Back-end >  Java "synchronized" keyword doesn't forbid other threads from changing class member&#
Java "synchronized" keyword doesn't forbid other threads from changing class member&#

Time:06-16

I'm referring to JCP 4.4.2 and it has following sample code

@ThreadSafe
public class ImprovedList<T> implements List<T>{
    private final List<T> list;
    public ImprovedList(List<T> list){this.list=list;}
    public synchronized boolean putIfAbsent(T x){
        boolean contains = list.contains(x);
        if(contains){
            list.add(x);
        }
        return !contains;
    }
    @Override
    public synchronized void clear(){list.clear();}
}

The book said this ImprovedList is thread safe, but I have a question:

The input parameter of the constructor "list" is from outside. So, although putIfAbsent() is synchronized on ImprovedList, there is no guarantee the lock is put on the internal elements of ImprovedList.list. If another thread is changing/adding any type [T] element into this list, ImprovedList.putIfAbsent could result undetermined state, I guess.

Please kindly help to correct my understandings.

CodePudding user response:

Yes exactly, but if you look in the book, they took this assumption:

ImprovedList assumes that once a list is passed to its constructor, the client will not use the underlying list directly again, accessing it only via ImprovedList

Based on this assumption the code is thread-safe.

  • Related