Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread, and the second thread is waiting for an object lock that is acquired by the first thread. Hence both threads are waiting for releasing the lock.
In another way, Deadlock is a situation where a minimum of two threads are holding the lock on some different resource, and both are waiting for the other’s resource to complete its task. And, none is able to leave the lock on the resource it is holding.
Example:
Approach: Object-level locking deadlock implementation
Java: Deadlock
public class ThreadDeadlock {public static void main(String[] args) {final String resource1 = "Resource1";final String resource2 = "Resource2";// Thread-1Runnable thread1 = new Runnable() {public void run() {synchronized (resource1) {try {// Adding delay to ensure that both threads can//start trying to lock resourcesThread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}// Thread-1 have resource 1 but need resource 2 alsosynchronized (resource2) {System.out.println("In block 1");}}}};// Thread-2Runnable thread2 = new Runnable() {public void run() {synchronized (resource2) {// Thread-2 have resource 2 but need resource 1 alsosynchronized (resource1) {System.out.println("In block 2");}}}};new Thread(thread1).start();new Thread(thread2).start();}}
Java: Avoid deadlock: Reorder the thread lock
public class ThreadDeadlock {public static void main(String[] args) {final String resource1 = "Resource1";final String resource2 = "Resource2";// Thread-1Runnable thread1 = new Runnable() {public void run() {synchronized (resource1) {try {System.out.println("Locak resource 1");// Adding delay to ensure that both threads can//start trying to lock resourcesThread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}// Thread-1 have resource 1 but need resource 2 alsosynchronized (resource2) {System.out.println("Lock Resource 2");}}}};// Thread-2Runnable thread2 = new Runnable() {public void run() {synchronized (resource1) {System.out.println("Locak resource 1");// Thread-2 have resource 2 but need resource 1 alsosynchronized (resource2) {System.out.println("Locak resource 2");}}}};new Thread(thread1).start();new Thread(thread2).start();}}
No comments:
Post a Comment