2

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

As I read about synchronizedList it only protect a single add, not bunch of adds.
Well, you could use addAll() to add a batch of items. Although your scenario is a bit unclear. Why is the main thread clearing the array? Is it removing the items and storing them somewhere else?
No, when user select another order I clear the list so new items get loaded from internet. If other threads add to it after clear they come at top of list.
@Ali It does, but you get around any compound operation by synchronized(jsonArray){. That locks access to not only the code within the block but also all operations on the list.
You have several threads downloading information into the same List? You might want to head over to the codereview side to see if you can't improve the architecture a bit.
1

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();
}

3 Comments

So, what I get is synchronized block doesn't lock the list totally, it only locks it from other adding thread in this case?
What if some thread starts adding while the main thread is performing clear operation?
synchronized(items) here blocks multiple simulatenous invocations of items.add(t). The clear routine due to lack of synchronization doesn't even know or care about the lock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.