-1

I have several data listeners, which may receive datasets roughly at the same time. They will iterate datasets and store data to the same ArrayList by using its method add(). Could this potentially cause any issues of some data items not being stored?

5
  • Are these all on the same thread? Are you removing any items? Commented Mar 12, 2017 at 7:02
  • These are updated from several Firebase result listeners - I'm not sure if they run on UI or separate threads. Not removing any items. Just want to join results, that I get by using several different filters. Commented Mar 12, 2017 at 7:07
  • So tell us what exactly 'roughly at the same time means'. In any case if you don't know it's single-threaded, you have to assume it isn't, and defend accordingly. Commented Mar 12, 2017 at 7:42
  • User may select 1 to 10 selections and accordingly 1 to 10 Firebase queries will be launched at the same time to retrieve these subsets from large dataset. Depending on the size of each subset, I guess these will be delivered within several seconds. Commented Mar 12, 2017 at 8:02

2 Answers 2

2

ArrayList is not synchronized. From the docs

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.)

You can use synchronizedList for this

List list = Collections.synchronizedList(new ArrayList(...));
Sign up to request clarification or add additional context in comments.

Comments

0

You can use synchronized block in this case :

synchronized (this){
    // ...
}

You can find a good examples here Synchronized

1 Comment

Any similar resource in English?

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.