views:

300

answers:

4

Duplicate: What is the most frequent concurrency problem you’ve encountered in Java?


I've been thinking of list of common programming mistakes/pitfalls that causes the code in Java is not thread safe. Here are the common ones that I encountered in the code through the recent years of Java development.

  • Using non-static fields within the singletons to hold the mutable state.
  • Use of static fields to hold the mutable state and often accessing those for other classes (publi static).
  • Using javax.servlet.ServletContext to hold mutable state as attributes.
  • (my No. 1, found in the code yesterday) Using system properties (System.getProperty() and System.setProperty()) to hold mutable state and accessing it is static way in various places in the code.

Can you share your experience on this field? I know that the human imagination is nearly unbounded, so I expect lots of other creative ways to beak the code that was meant to be thread safe.

One more remark: The assumption is that there is no synchronization.

+1  A: 

Mutable state seems to be a common culprit amongst all of your pitfalls. I'm hesitant to say it, but does "not using message passing" seem as if it might be a pitfall?

Curt Sampson
+3  A: 

Using any shared state without appropriate synchronization or the use of the java.util.concurrent.atomic classes is problematic.

Using system properties to hold mutable state sounds like a very bad idea in general.

Assuming there is no synchronization, your options are very limited. It's a much better idea to synchronize when you need to access shared, mutable state apart from very specific scenarios where the atomic types make sense. Correct lock-free code is very hard - I don't suggest trying it unless you're an expert.

Jon Skeet
A: 

When developing web applications: use of plain HashMaps, which are stored per application or per session, on which every request puts into and gets.

this caused two dead threads in my application with no way of recovery except a total restart.

Andreas Petersson
+1  A: 

I often encountered this one (which is a special case of the first in your list):

Storing user state in Servlet instance variables.

rudolfson