Home  >  Article  >  Java  >  How Can You Ensure Thread-Safety for an ArrayList of Thread Objects in Java?

How Can You Ensure Thread-Safety for an ArrayList of Thread Objects in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 01:47:03460browse

How Can You Ensure Thread-Safety for an ArrayList of Thread Objects in Java?

Ensuring Thread-Safety of an ArrayList in Java

Issue: An ArrayList used to store Thread objects (RaceCar) in a racing simulation requires thread safety to maintain the correct order of finishers. The initial attempt to synchronize the ArrayList using Collections.synchronizedCollection() resulted in a compiler error.

Analysis:
Collections.synchronizedCollection() can only synchronize non-List Collection implementations. To synchronize an ArrayList specifically, use Collections.synchronizedList().

Solution:

<code class="java">finishingOrder = Collections.synchronizedList(new ArrayList<>(numberOfRaceCars));</code>

This code correctly creates a thread-safe ArrayList to store RaceCar objects and maintain the order of finishers.

The above is the detailed content of How Can You Ensure Thread-Safety for an ArrayList of Thread Objects in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn