Understanding the Scope of Multi-Threaded Variables

Asked 1 years ago, Updated 1 years ago, 55 views

Thank you for your help.
Regarding the subject,
under the multi-threaded environment of java ConcurrentModificationException occurred because of using the instance variable in new ArrayList().
Also, I heard that if you use new ArrayList() as the variable in the method, it becomes a local variable, so it becomes thread safe.
So, ArrayList is an asynchronous class, but can it still be used as a thread-safe variable within the method?Please let me know

java

2022-09-30 21:34

1 Answers

Short Answer:ArrayList is not inherently thread safe.If you need a thread-safe list, use Collections.synchronizedList.

List<X>list=Collections.synchronizedList (new ArrayList<>());

I heard that if you use new ArrayList() as the variable in the method, it becomes a local variable, so it becomes thread safe.

It's a mistake.There is no correlation between the scope of the variable and thread safe.Thread safe or not is an external specification for the class or method.

ArrayList is an asynchronous class, but can it still be a thread-safe variable within the method?

No, but if one instance is referenced only by the local variable in the method, it cannot be manipulated by other threads, so the result is no accident.


2022-09-30 21:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.