user3663882
user3663882

Reputation: 7357

Reading and writing to a collection

I have the following class:

public class GroupsContainer{

    private final List<Group> col;

    public synchronized Group get(int ids){
            return col.get(ids);
    }

    public synchronized void add(Group g){
            col.add(g);
    }
}

Now suppose some thread wanted to get all elements from 0 to 10:

List<Group> lst;
GroupContainer gc;
//staff
for(int i = 0; i < 10; i++)
    lst.add(gc.get(i));

and at the same time another thread is trying to write new elements from 0 to 10:

List<Group> lst;
GroupContainer gc;
//staff
for(int i = 0; i < 10; i++)
    gc.add(i, lst.get(i));

I need to do the following:

Once the writer release the monitor, the reader should block all writer's thread right after that and shouldn't allow writer to write something else until it's finished with reading.

Is it possible to do? With the current implementation it won't work.

Upvotes: 0

Views: 143

Answers (1)

JP Moresmau
JP Moresmau

Reputation: 7403

Each of your method is synchronized, but you want to synchronize several invocations of them (10 in your example). you could simply wrap your code in a synchronized block:

 synchronized(gc){
    for(int i = 0; i < 10; i++)
        lst.add(gc.get(i));
}

Upvotes: 2

Related Questions