java - The set(int index, E element) method in ArrayList does not need to be synchronized in the case of multi-threading
为情所困
为情所困 2017-05-27 17:40:40
0
2
714

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))));
      }
为情所困
为情所困

reply all(2)
阿神

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template