Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
Based on number of Threads ( tasks complexity ) and priority Thread Scheduler decides execution plan. Here my intention is to generate DeadLock so I planned to execute both threads 10 times so that at sometime they will be blocked for locks !
Problem : Many times we tag records/ Objects for better indexing. Though this will
not be real time problem but I am trying to simulate a similar scenario.
say for some requirement I am tagging a customer with an Address and again
Address with Customer in a social media Analytic Application. To do this
tasks I may need thousands of Threads.
Below is one code which may report deadlock for such Threads.
===========================================================================================
public class CustomerUpdateDeadloackThread { public static void main(String[] args) { Customer cstmr = new Customer("Peter"); Address adrs = new Address("B-232, Bangalore"); for (int i=0; i<10;i++){ // Lets tag a customer and address with each other for indexing new Thread(new TagObjectsToEachOther(cstmr, adrs)).start(); new Thread(new TagObjectsToEachOther(adrs, cstmr)).start(); } } } interface CustomerUpdater { public boolean update(Object obj); } class TagObjectsToEachOther implements Runnable { CustomerUpdater taskItem; Object objToUpdateWith; public TagObjectsToEachOther(CustomerUpdater cspdtr, Object obj2) { this.taskItem = cspdtr; this.objToUpdateWith = obj2; } @Override public void run() { taskItem.update(objToUpdateWith); System.out.println(" Task done :" + Thread.currentThread().getName()); } } class Address implements CustomerUpdater { String address; Customer customer; public Address(String addrs) { this.address = addrs; } @Override public boolean update(Object cstmr) { synchronized (this) { synchronized ((Customer) cstmr) { try { this.customer = (Customer) cstmr; Thread.sleep(2000); // or else do some other work here so that lock gets used for some more time } catch (CustomerUpdateFailureException e) { e.getCause(); return false; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } } } } class Customer implements CustomerUpdater { String name; Address address; public Customer(String nm) { this.name = nm; } @Override public boolean update(Object adrs) { synchronized (this) { synchronized ((Address) adrs) { try { this.address = (Address) adrs; Thread.sleep(2000); // or else do some other work here so that lock gets used for some more time } catch (CustomerUpdateFailureException e) { e.getCause(); return false; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } } } } class CustomerUpdateFailureException extends RuntimeException { private static final long serialVersionUID = 1L; @Override public String getMessage() { return "Uncompitable update"; } }