kaoziun
kaoziun

Reputation: 53

Thread - Enhanced for - java

I'm just asking if is thread-safe to use

I precise that "doSomething()" is thread-safe.

Upvotes: 2

Views: 71

Answers (3)

Flic
Flic

Reputation: 751

Thread safety depends on the Collection over which you are iterating, not the use of enhanced for. If the Collection is synchronized or you are not modifying the Collection, it is Thread safe. ArrayList<> is not synchronized by default.

Upvotes: 2

dursun
dursun

Reputation: 1846

It is not thread safe if it is possible that another can modify compo variable, or any element in compo variable. you can use ImmutableList to be sure that it is not modified.

Upvotes: 1

Eran
Eran

Reputation: 393936

If doSomething() modifies the state of the Component instance (which it probably does, since it looks like it has no return value), then no, it's not thread safe. You'll have to take care of the thread safety yourself.

Upvotes: 1

Related Questions