Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java avoid race condition WITHOUT synchronized/lock

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

like image 472
cn1h Avatar asked Dec 01 '11 11:12

cn1h


2 Answers

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.

like image 200
AlexR Avatar answered Nov 15 '22 05:11

AlexR


Atomics are indeed more efficient than classic locks due to their non-blocking behavior i.e. a thread waiting to access the memory location will not be context switched, which saves a lot of time.

Probably the best guideline when synchronization is needed is to see how you can reduce the critical section size as much as possible. General ideas include:

  1. Use read-write locks instead of full locks when only a part of the threads need to write.
  2. Find ways to restructure code in order to reduce the size of critical sections.
  3. Use atomics when updating a single variable.
  4. Note that some algorithms and data structures that traditionally need locks have lock-free versions (they are more complicated however).
like image 26
Tudor Avatar answered Nov 15 '22 05:11

Tudor