Home  >  Q&A  >  body text

java - The set(int index, E element) method in ArrayList does not need to be synchronized in the case of multi-threading

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

reply all(2)I'll reply

  • 阿神

    阿神2017-05-27 17:42:40

    Non-thread safety means that all operations of List are not locked. So you need to control the lock in your own business thread.

    reply
    0
  • 为情所困

    为情所困2017-05-27 17:42:40

    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

    reply
    0
  • Cancelreply