Home > Software engineering >  Do I need to use a threadsafe collection when I synchronize my getters and setters?
Do I need to use a threadsafe collection when I synchronize my getters and setters?

Time:11-02

Let's say I've a class that contains a simple list container and all my setters and getters are synchronized. Do I have to use a thread-safe collection in that case to have it all thread safe or because of synchronized getters and setters it's okay? For example.

    public class Threads<T> implements Buffer<T>{

        private LinkedList<String> list;

        public Threads(Object s) {
            // ...
        }
        
        synchronized public void put(T t) {
            // ...
        }

        synchronized public T get() {
            // ...
        }
        
    }

CodePudding user response:

I presume that the "it" you refer to is the s parameter.

You need to declare the s parameter and s field with type Buffer<T>. Something like this:

public class Threads<T> implements Buffer<T>{
    Buffer<T> s;

    public Threads(Buffer<T> s) { 
        this.s = s;
    }
    
    synchronized public void put(T t) {
        s.put(t);
    }

    synchronized public T get() {
        return s.get();
    }
}

At this point you have implemented a thread-safe wrapper for a Buffer<T>. But it is only thread safe with respect to operations performed using the wrapper methods.

(This Buffer<T> class / interface must be something that you have designed yourself. The standard java.nio.Buffer class isn't parameterized, and it doesn't provide get and put methods. The subclasses of java.nio.Buffer do have get and put methods, but they are not related to each other at the type level.)

  • Related