This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Concurrency and java.util.List Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Concurrency and java.util.List" Watch "Concurrency and java.util.List" New topic

Concurrency and java.util.List

Bojan Mihaljevic

Joined: Jun 01, 2005
Posts: 4

I have an ArrayList that is being used by multiple threads to save information. For efficiency sake, I would like to avoid synchronizing block of code whenever posible. Now, I guess ArrayList's add() method is not an atomic "operation" and it can be interrupted, but can that concurrent insertion of elements produce any unwanted concequences apart from maybe storing the information in a "strange" order. It would be really nice if anyone could help me out with this, or suggest a better way to store information from multiple threads in one "place".
Henry Wong

Joined: Sep 28, 2004
Posts: 18545

Highly *not* recommended. If you are lucky, you will lose data, meaning an entry might overwrite another entry. If you are not, internal counters will be incorrect, causing all sorts of problems.

Two points...

First, if you are using Java 5.0, look into either the ConcurrentHashMap, or the ConcurrentLinkedQueue. Neither one is a list, but both allow parallel reads, and sometimes parallel writes, and both are thread safe. And you might be able to use it with a small algorithm change.

And second, why?!?!? The operations are incredibly fast, mainly because they are incredibly simple. Isn't there better options to improving the speed of your code than to purposely try to live with race conditions?


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Bojan Mihaljevic

Joined: Jun 01, 2005
Posts: 4
Thank you Henry. I read about the util.concurrent package, but I am using Java 1.4.2. Since you say there is no big performance overhead I will just use the synchronization technique. Thanks alot.

Timmy Marks
Ranch Hand

Joined: Dec 01, 2003
Posts: 226
Hi Joe,

since you are using Java 1.4, you can use Doug Lea's concurrency package or, as recommended on the site, Dawid Kurzyniec's backport of the main java.util.concurrent classes (I couldn't get the second URL to work).

The java.util.concurrent package in Java 5 is taken largly from Professor Lea's package.
wood burning stoves
subject: Concurrency and java.util.List
Similar Threads
Using multithreading for Backup Process
HashMap or HashTable
why wait()/notify() methods are in Object class?
Threads - overview
concurrent threads