Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered lists and class thread-safety

I have a class which has:

  • 2 fields holding time-ordered list (list1, list2).
  • 3 read-only methods which iterate above lists to generate summary statistics.
  • 1 mutating method, which looks for a match of given 'new-item' in list1. If match is not found, it adds 'new-item' to list1. If match is found, it removes the match from list1 and adds both match and 'new-item' to list2.

Lets assume that multiple concurrent invocation of all methods are possible. I need to achieve thread-safety while maximising performance.

Approach1 (extremely slow) - Declare field-types as ArrayList and use synchronise keyword on all methods.

Approach2 - Declare field-type as CopyOnWriteArrayList and synchronise the mutating method.

Questions

  1. Does Approach2 ensure thread-safety?
  2. Are there better alternatives?
like image 463
Shruti Tiwari Avatar asked Aug 20 '15 15:08

Shruti Tiwari


People also ask

Which collection classes are thread-safe?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

Are class variables thread-safe?

Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately.

How do I make sure my class is thread-safe?

To make these classes thread-safe, you must prevent concurrent access to the internal state of an instance by more than one thread. Because Java was designed with threads in mind, the language provides the synchronized modifier, which does just that.

Is a list thread-safe?

A thread-safe variant of ArrayList in which all mutative operations (e.g., add, set, remove..) are implemented by creating a separate copy of an underlying array. It achieves thread safety by creating a separate copy of the List which is different than vector or other collections used to provide thread-safety.


1 Answers

Do you need the random access offered by an ArrayList? Can you instead use a thread-safe ordered collection like ConcurrentSkipListSet (non-blocking) or PriorityBlockingQueue (blocking)? Both have log(n) insertions.

Mutation methods in both cases are thread-safe.

Edit: Just note, you would still run into atomicity concerns. If you need the add's to be done attomically then you would need more coarse locking.

like image 163
John Vint Avatar answered Oct 04 '22 07:10

John Vint