Directly accessible data structure Java -


i have following situation:

  1. a data structure can ever extended ( ever add things in tail)
  2. i need able keep track of elements have seen (i have index, , ideally want able start traversing list again particular element)
  3. i reads never blocking, , addition of new element ever lock tail of queue rather whole queue

this structure heavily modified multiple threads.

what best data structure this?

arraylist. ideal able directly access last element seen using index, leads concurrent modifications exceptions. make synchronised, avoid locking (or locking apart last element, 1 there might concurrent writes add new elements)

concurrentlinkedqueue. solve concurrency problem, has problem have store current position of iteration rather integer index. has problem returns weakly consistent iterator not guaranteed return new objects have been added list since iterator created (source: javadoc)

concurrenthashmap index keys. has benefit can access data corresponding correct index directly, has issue there isn't "getnext" operator allow me efficiently traverse elements index, index + 1, etc

vectors solve of problems in allowing won't throw concurrent modification exceptions , allow direct accessing. however, given methods synchronised, performance poor compared arraylists. given ever want extend structure, , not insert records in middle, i'm reluctant go heavy weight solution, reads suffer performance hit (whereas, given usecase, index of element never changes, there's no need synchronise reads not tail)

custom data structure: keep array of objects want store , pointer tail of array (the last element set), when inserting new object, lock tail , object pointed tail. when object exceeds current size, locking resize operation.

what best strategy/ other more efficient implementation?

the copyonwritearraylist structure solve problem (java.util.concurrent).

  • copyonwritearraylists thread-safe because mutative operations implemented creating copy of list.

  • the problem of concurrentmodificationexception avoided because array doesn't change while iterated. called snapshot style iterator uses reference state of array when iterator created.

  • if have more reads writes, use copyonwritearraylist, otherwise use vector.

  • vector introduces small synchronization delay each operation, when copyonwritearraylist has longer delay write (due copying) no delay reads.

  • vector requires explicit synchronization when iterating (so write operations can't executed @ same time), copyonwritearraylist doesn't.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -