What to use in multithreaded environment; Vector or ArrayList?

Actually both ArrayList and Vector are very bad choices here, not because of synchronization (which you would definitely need), but because removing the first element is O(n) The perfect data structure for your purspose is the ConcurrentLinkedQueue : it offers both thread safety (without using synchronization), and O(1) adding and removing.

Actually both ArrayList and Vector are very bad choices here, not because of synchronization (which you would definitely need), but because removing the first element is O(n). The perfect data structure for your purspose is the ConcurrentLinkedQueue: it offers both thread safety (without using synchronization), and O(1) adding and removing.

1 ArrayDeque also gives O(1), but probably faster though without the thread-safety. – Tom Hawtin - tackline Aug 23 '10 at 12:29.

It not please consider using java.util.concurrent. LinkedBlockingQueue for this kind of stuff.It's really worth looking at java.util.concurrent. * package when dealing with concurrency.

1 BlockingQueues are the way to go for producer/consumer pattern. – Markus Kull Aug 23 '10 at 12:28.

There actually is a marginal difference in performance between a sychronizedlist and a vector. (javacodegeeks.com/2010/08/java-best-prac...).

Vector is worse than useless. Don't use it even when using multithreading. A trivial example of why it's bad is to consider two threads simultaneously iterating and removing elements on the list at the same time.

The methods size(), get(), remove() might all be synchronized but the iteration loop is not atomic so - kaboom. One thread is bound to try removing something which is not there, or skip elements because the size() changes. Instead use synchronized() blocks where you expect two threads to access the same data.

Private ArrayList myList; void removeElement(Object e) { synchronized (myList) { myList. Remove(e); } } Java 5 provides explicit Lock objects which allow more finegrained control, such as being able to attempt to timeout if a resource is not available in some time period. 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(); } }.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions