What to use in a multi-threaded environment; Vector or ArrayList

I have this situation:

Web application with 200 consistent requests (Threads) need to write something to the local file system. I have one class to which all threads place their calls, and this class internally stores messages in a single array (Vector or ArrayList), which then, in turn, will be written to the file system.

The idea is to return from the ASAP call flow so that the thread can do this work as quickly as possible, what the thread wanted to write to the log can be written to the file system later, this is not so important.

So, this class, in turn, removes the first element from this list and writes it to the file system, while in real time there are 10 or 20 threads that add new logs at the end of this list.

I would like to use an ArrayList since it is not synchronized, and so the calls to the threads will be less, the question is

Am I at risk of facing / data loss? Is it better to use a Vector because it is thread safe? Is it slower to use Vector?

+3
source share
4 answers

In fact, both ArrayListand Vectorare very bad choice here, not because of synchronization (which you definitely need to), but because the removal of the first element - O (n).

- ConcurrentLinkedQueue: ( ), O (1 ) .

+16

() Java? java.util.concurrent.LinkedBlockingQueue . java.util.concurrent. * concurrency.

+2

, . . , , - , . size(), get(), remove() , so-kaboom. -, , , ().

synchronized(), , .

private ArrayList myList;

void removeElement(Object e)
{
  synchronized (myList) {
    myList.remove(e);
  }
}

Java 5 provides explicit Lock objects that allow you to control a smaller font, for example, the possibility of trying to timeout if the resource is unavailable for a certain period of time.

private final Lock lock = new ReentrantLock();
private ArrayList myList;

void removeElement(Object e) {
{
  if (!lock.tryLock(1, TimeUnit.SECONDS)) {
    // Timeout
    throw new SomeException();
  }
  try {
    myList.remove(e);
  }
  finally {
    lock.unlock();
  }
}
+1
source

In fact, there is a marginal performance difference between a synchronized list and a vector. ( http://www.javacodegeeks.com/2010/08/java-best-practices-vector-arraylist.html )

0
source

Source: https://habr.com/ru/post/1761099/


All Articles