Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: Concurrency control for access to list in java

I have a multi-threaded application that has a centrlaised list that is updated (written to) only by the main thread. I then have several other threads that need to periodically retrieve the list in its current state. Is there a method that can allow me to do this?

like image 934
pie154 Avatar asked Oct 15 '10 14:10

pie154


People also ask

Is there a concurrent list in java?

There is a concurrent list implementation in java. util. concurrent. CopyOnWriteArrayList in particular.

How do you manage concurrency in java?

The simplest way to avoid problems with concurrency is to share only immutable data between threads. Immutable data is data which cannot be changed. To make a class immutable define the class and all its fields as final. Also ensure that no reference to fields escape during construction.

How do you restrict the size of a list in java?

Java ArrayList trimToSize() Method example trimToSize() method is used for memory optimization. It trims the capacity of ArrayList to the current list size.

How does ReentrantLock work in java?

A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.


2 Answers

That depends on how you want to restrict the concurrency. The easiest way is probably using CopyOnWriteArrayList. When you grab an iterator from it, that iterator will mirror how the list looked at the point in time when the iterator was created - subsequent modifications will not be visible to the iterator. The upside is that it can cope with quite a lot of contention, the drawback is that adding new items is rather expensive.

The other way of doing is locking, the simplest way is probably wrapping the list with Collections.synchronizedList and synchronizing on the list when iterating.

A third way is using some kind of BlockingQueue and feed the new elements to the workers.

Edit: As the OP stated only a snapshot is needed, CopyOnWriteArrayList is probably the best out-of-the-box alternative. An alternative (for cheaper adding, but costlier reading) is just creating a copy of a synchronizedList when traversion is needed (copy-on-read rather than copy-on-write):

List<Foo> originalList = Collections.synchronizedList(new ArrayList());

public void mainThread() {
    while(true)
        originalList.add(getSomething());
}

public void workerThread() {
    while(true) {
        List<Foo> copiedList;
        synchronized (originalList) {
             copiedList = originalList.add(something);
        }
        for (Foo f : copiedList) process(f);
    }
}

Edit: Come to think of it, the copy-on-read version could simplified a bit to avoid all synchronized blocks:

List<Foo> originalList = Collections.synchronizedList(new ArrayList());

public void mainThread() {
    while(true)
        originalList.add(getSomething());
}

public void workerThread() {
    while(true) {
        for (Foo f : originalList.toArray(new Foo[0])) 
            process(f);
    }
}

Edit 2: Here's a simple wrapper for a copy-on-read list which doesn't use any helpers, and which tries to be as fine-grained in the locking as possible (I've deliberately made it somewhat excessive, bordering on suboptimal, to demonstrate where locking is needed):

class CopyOnReadList<T> {

    private final List<T> items = new ArrayList<T>();

    public void add(T item) {
        synchronized (items) {
            // Add item while holding the lock.
            items.add(item);
        }
    }

    public List<T> makeSnapshot() {
        List<T> copy = new ArrayList<T>();
        synchronized (items) {
            // Make a copy while holding the lock.
            for (T t : items) copy.add(t);
        }
        return copy;
    }

}

// Usage:
CopyOnReadList<String> stuff = new CopyOnReadList<String>();
stuff.add("hello");
for (String s : stuff.makeSnapshot())
    System.out.println(s);

Basically, when you to lock when you:

  1. ... add an item to the list.
  2. ... iterate over the list to make a copy of it.
like image 93
gustafc Avatar answered Sep 30 '22 19:09

gustafc


You can consider using a read - write lock mechanism. If your JDK version is 1.5 or newer, you can use ReentrantReadWriteLock.

like image 22
hakan Avatar answered Sep 30 '22 17:09

hakan