Tag Archives:

Java Generics and Collections in Action

On Monday, Maurice Naftalin, co-author of the Book Java Generics and Collections presented a talk about two new features in Java5/6:

  • Generics
  • (Concurrent) Collections

Generics

Maurice started by stating the advantages of using generics. These include the following:

  • cleaner code (eg. the enhanced for-loop; no casts)
  • more errors can be detected at compile time (which would otherwise only be noticed at run time)

Maurice then talked about the ‘by erasure’ implementation of generics that makes it possible to gradually ‘generify’ legacy libraries and your client code.

(Concurrent) Collections

Collections in Java (since v1.2) are by default not thread safe, which means that two threads can simultanuously read/write to a Collection, possiby leaving the Collection in an inconsistent state.

Thread safe Collections are also available, but note that this is not the same as concurrent safe access. Eg. when iterating (which is obviously is not an atomic operation) over a thread safe collection you’ll receive a ConcurrentModificationException when the underlying collection is modified. (a so-called fail-fast iterator)

The java.util.concurrent package introduce weakly consistent iterators. Weakly consistent iterators may or may not reflect insertions made during iteration, but they will definitely reflect updates or removals for keys that have not yet been reached by the iterator, and will not return any value more than once.

Here is a summarized list of the non thread safe and new java.util.concurrent Collection interfaces and when to use them. (Remember to choose your collection based on functional behaviour, performance characteristics and concurrency policies.)

  • Queues
    • Not threadsafe with FIFO ordering
      • ArrayDeque
      • PriorityQueue
    • Threadsafe (with weakly consistent iterator)
      • PriorityBlockingQueue
      • DelayQueue
      • ConcurrentLinkedQueue: best non blocking threadsafe queue
  • Lists
    • Threadsafe (with weakly consistent iterator)
      • CopyWriteArrayList: good when you have more reads then writes
    • Non thread safe
      • ArrayList: best general purpose list
      • LinkedList: only ok qua performance when using a ListIterator (which provides remove, add and iteration operations) – never do access by index => slow!!
  • Sets
    • Non thread safe
      • HashSet
      • LinkedHashSet: this set keeps O(1) when the set is almost full
      • EnumSet: optimized for using Enums objects
    • Threadsafe (with weakly consistent iterator)
      • CopyInWriteArrayList: good when you have more reads then writes