I know that ArrayList is a thread-unsafe class. In multi-threaded situations, add() and remove() cannot be performed directly, but can I use the set(int index, E element) method?
List<T> records = InstanceUtil.newArrayList();
for (int i = 0; i < ids.getRecords().size(); i++) {
records.add(null);
}
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < ids.getRecords().size(); i++) {
final int index = i;
executorService.execute(() -> records.set(index, queryById(ids.getRecords().get(index))));
}
Non-thread safety means that all operations of List are not locked. So you need to control the lock in your own business thread.
Looking at this logic, each index value can only be accessed (assigned) by one thread, and there is no multi-threading access to the same index