These are some guidelines using which we can avoid most of the deadlock situations.
Avoid Nested Locks: This is the most common reason for deadlocks, avoid locking another resource if you already hold one. It’s almost impossible to get a deadlock situation if you are working with only one object lock.
Lock Only What is Required: You should acquire lock only on the resources you have to work on, for example if I am locking the complete Object resource but if we are only interested in one of its fields, then we should lock only that specific field not the complete object.
Avoid waiting indefinitely: You can get deadlock if two threads are waiting for each other to finish indefinitely using thread join. If your thread has to wait for another thread to finish, it’s always best to use a join with maximum time you want to wait for the thread to finish.