Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing the best concurrency list in Java [closed]

My thread pool has a fixed number of threads. These threads need to write and read from a shared list frequently.

So, which data structure (it better be a List, must be monitor-free) in java.util.concurrent package is best in this case?

like image 416
象嘉道 Avatar asked Nov 20 '11 18:11

象嘉道


People also ask

How do you avoid concurrency issues in Java?

The simplest way to avoid problems with concurrency is to share only immutable data between threads. Immutable data is data which cannot be changed. To make a class immutable define the class and all its fields as final. Also ensure that no reference to fields escape during construction.

Is list in Java thread-safe?

It implements List interface. It is a thread-safe variant of ArrayList.

Is there any concurrent list in Java?

There is a concurrent list implementation in java.

Is ArrayList thread-safe Java?

Vectors are synchronized. Any method that touches the Vector 's contents is thread safe. ArrayList , on the other hand, is unsynchronized, making them, therefore, not thread safe.


2 Answers

had better be List

The only List implementation in java.util.concurrent is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.

That said, are you sure you need it to be a List? There are a lot more options for concurrent Queues and Maps (and you can make Sets from Maps), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.

For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:

  • ConcurrentLinkedQueue
  • ArrayBlockingQueue
  • LinkedBlockingDeque
  • LinkedBlockingQueue
  • PriorityBlockingQueue
  • SynchronousQueue
  • DelayQueue
like image 57
ColinD Avatar answered Nov 15 '22 15:11

ColinD


Any Java collection can be made to be Thread-safe like so:

List newList = Collections.synchronizedList(oldList);

Or to create a brand new thread-safe list:

List newList = Collections.synchronizedList(new ArrayList());

http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList(java.util.List)

like image 44
Travis Webb Avatar answered Nov 15 '22 15:11

Travis Webb