Java avoid race condition WITHOUT synchronized/lock

cn1h picture cn1h · Dec 1, 2011 · Viewed 15.1k times · Source

In order to avoid race condition, we can synchronize the write and access methods on the shared variables, to lock these variables to other threads.

My question is if there are other (better) ways to avoid race condition? Lock make the program slow.

What I found are:

  • using Atomic classes, if there is only one shared variable.
  • using a immutable container for multi shared variables and declare this container object with volatile. (I found this method from book "Java Concurrency in Practice")

I'm not sure if they perform faster than syncnronized way, is there any other better methods?

thanks

Answer

AlexR picture AlexR · Dec 1, 2011

Avoid state.
Make your application as stateless as it is possible.
Each thread (sequence of actions) should take a context in the beginning and use this context passing it from method to method as a parameter.

When this technique does not solve all your problems, use the Event-Driven mechanism (+Messaging Queue).
When your code has to share something with other components it throws event (message) to some kind of bus (topic, queue, whatever).

Components can register listeners to listen for events and react appropriately.
In this case there are no race conditions (except inserting events to the queue). If you are using ready-to-use queue and not coding it yourself it should be efficient enough.

Also, take a look at the Actors model.