Ali
Ali

Reputation: 22337

Java List Synchronization

I have an ArrayList which is accessed by multiple threads. Main thread only clears the list and others add to it. I don't want the list get cleared while another thread is adding item to it. I want the list is locked while thread is adding item to it.

this is the code of adding thread:

synchronized (items)
{
    int length = jsonArray.length();
    if ((length > 0)) for (int i = 0; i < length; i++)
    {
        items.add(new Item(jsonArray.getJSONObject(i)));
    }
}

But I don't use synchronized block for clearing. Is synchronized block necessary for clear too?

Upvotes: 2

Views: 378

Answers (2)

Kayaman
Kayaman

Reputation: 73578

A quick way to handle this is to just use

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

All the methods will be synchronized and you'll be safe.

If anyone comments here something about performance, provide actual data of the OP's scenario to back up your claims.

Upvotes: 2

Johan Sj&#246;berg
Johan Sj&#246;berg

Reputation: 49237

I don't want the list get cleared while another thread is adding item to it.

Then yes, you need to have the clear routine synchronized as well.

In the below sample, the synchronized statement in add does not block clear.

public void add(T t) {
   synchronized(items) {
      items.add(t);
   }
}

public void clear() {
   items.clear();
}

Upvotes: 1

Related Questions