-1

Lets imagine I have the following code:

class ClassA {
    final Integer i;
    final String;
    final CopyOnWriteArrayList<ClassB> l;
    ClassA() { ...
    }
}

class ClassB {
    final Integer i;
    final String;
    ClassB() { ...
    }
}

class ClassC {
    final CopyOnWriteArrayList<ClassA> cache = new CopyOnWriteArrayList<>();

    ClassA get() {
        return cache.get(...)
    }

    void updateV1() {
        cache.add(new ClassA(...))
    }

    void updateV2() {
        cache.get(...).l.add(new ClassB(...))
    }
}

Is it thread-safe by itself cause of using final keyword for all fields and making all lists CopyOnWriteArrayList? Looks like there is no problems with ConcurrentModificationException and reordering could not broke the state? Is it true? Or I should provide some additional defence via synchronization/Locks?

0

1 Answer 1

0

"Thread safety" is not an attribute of data structures. It's an attribute of the code that accesses the data structures. When we call a class "thread safe," that's a shortcut way of saying that the class's data members are all private, and the class's methods only access the private data in thread-safe ways.

Your classes have no real methods,* and their data members are all effectively public. So, it only makes sense to ask about the thread safety of the code that uses your classes. It doesn't make any sense to say that the classes themselves are thread safe or not thread safe.


*Getters and setters are don't operate on data, they just make the data public.

Not the answer you're looking for? Browse other questions tagged or ask your own question.