user3663882
user3663882

Reputation: 7357

Allow only one thread at the time to use an object

I have the following class:

public class MyClass{

    private List<Integer> ints = new LinkedList<Integer>();

    public List<Integer> getInts(){
        return ints;
    }

    public synchronized void doAction(){ 
        //Do some with the list
    }
}

I need to allow only one thread at the time having acces to the List. I would do that as follows:

public class MyClass{

    private List<Integer> ints = new LinkedList<Integer>();
    private static final Semaphore s = new Semaphore(1);

    public List<Integer> getInts(){
        s.acquire();
        return ints;
    }

    public void release(){
        s.release();
    }

    public synchronized void doAction(){ 
        s.acquire();
        //Do some with the list
        s.release();
    }
}

But the implementaion is obviously not reliable, because if the client request the List through the getter for adding some elements into it and forget to call release() we'll get into troubles if try to invoke the doAction method.

What is the solution for the problem?

Upvotes: 1

Views: 863

Answers (2)

davidgiga1993
davidgiga1993

Reputation: 2853

You could use a synchronized list:

private List<Integer> ints = Collections.synchronizedList(new LinkedList<Integer>());

Upvotes: 2

Kayaman
Kayaman

Reputation: 73558

Don't allow the client to get the reference. Put all the methods that work on the list to MyClass and synchronize them.

You can allow the users to get a snapshot copy of the list however.

Upvotes: 4

Related Questions