Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Concurrency and java.util.List

 
Bojan Mihaljevic
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

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".
Thanks,
Joe
 
Henry Wong
author
Marshal
Pie
Posts: 21407
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Henry
 
Bojan Mihaljevic
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Joe
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic