how can I avoid race condition and deadlocks in a java multi threading environment where all the threads share a common resource.
thanks
Printable View
how can I avoid race condition and deadlocks in a java multi threading environment where all the threads share a common resource.
thanks
If you have only one resource that must be locked deadlocks can not be a problem, since deadlocking occurs only when thread A has acquired lock 1, thread B has acquired lock 2 and A needs to acquire lock 2 and B needs to acquire lock 1.
A race condition can always occur if the shared resource is mutable and not thread safe. In a simple case making the method which sets the value of the shared resource (and this method is part of the resource itself) synchronized should do the trick.