Posts

Showing posts with the label Java Deadlocks

How To Avoid Deadlock In java

How to avoid deadlocks One of the best ways to prevent the potential for deadlock is to avoid acquiring more than one lock at a time, which is often practical. However, if you have to acquire more then one lock for some purpose then acquire multiple locks in a consistent, defined order. Depending on how your program uses locks, it might not be complicated to ensure that you use a consistent locking order. You can define a lock acquisition ordering on the set of locks and ensure that you always acquire locks in that order. Once the lock order is defined, it simply needs to be well documented to encourage consistent use throughout the program. Following are the zest about how we can avoid deadlock in the context of java, Narrow down the synchronization's scope to as small a block as possible. Try to avoid locking multiple objects if possible.  Use a consistent lock order, by which if multiple locks need to be acquired will be acquired in a p...

What Is Deadlock In java

A condition that occurs when two processes are each waiting for the other to complete before proceeding. The result is that both processes hang . Deadlocks occur most commonly in multitasking and client/server environments. Ideally, the programs that are deadlocked, or the operating system , should resolve the deadlock, but this doesn't always happen. The Following examples depicts how we can have deadlock in java. p ublic class MyDeadlockTest {   public static void main(String[] args)   {     final Object object1 = "object1" ;     final Object object2 = "object2" ;     // t1 tries to lock object1 then object2     Thread t1 = new Thread()     {       public void run()       {         // Lock resource 1         synchronized (object1)         {           System...