Home > Mobile >  Java Thread safety questions
Java Thread safety questions

Time:11-03

I bumped into an exercise and I am no java guru to know how to implement that. My objective is to implement a generic interface, that has a getter and setter method. In It's constructor I have to put an s object that implements this generic interface. We have to Store this object in our class and use this class's getter and setters to implement our classes getters and setters(delegation).

public class Threads<T> implements Buffer<T>{
    Object s;
    public Threads(Object s) { // we know, that It implements our Buffer interface
        this.s=s;//i have no clue to what I should convert it.
    }
    
    synchronized public void put(T t) {
        //i don't know how to call s's put method
    }
    synchronized public T get() {
        //I don't know how to call s's get method.
        
    }
    
}

My question is: how do I deal with the parts of the code above where I have indicated in the comments that I don't know what to write?

Any ideas?

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