Reputation: 193
I have created a list of objects and also list of threads which the parameter sent is a random object from the list. Once the thread is created, the thread should lock on the object passed in the parameter. However, although I have set the thread to sleep after creating it to form deadlock. There doesnt seem to be any deadlock formed. Based on some google research, I learned that object is pass by reference in java however I m not sure why it is not working here.
for(int i=0;i<5;i++){
Object tempObject = new Object();
objectList.add(tempObject);
}
Random rand = new Random();
for(int i =0;i<5;i++){
for(int j =0;j<10;j++){
int random = rand.nextInt(objectList.size());
CustomThread ct = new CustomThread(i,objectList.get(random));
ct.start();
System.out.println();
}
try {
detectDeadlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void detectDeadlock() throws InterruptedException {
while(true){
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
long[] threadIds = threadBean.findDeadlockedThreads();
int deadlockedThreads = threadIds != null? threadIds.length : 0;
System.out.println("Number of deadlocked threads: " + deadlockedThreads);
TimeUnit.MILLISECONDS.sleep(1000);
}
}
CustomThread.java
NewThread(int processID, Object tObject) {
this.pid = processID;
this.object = tObject;
}
@Override
public void run() {
synchronized (this.object) {
Random rand = new Random();
System.out.println("Holding an object");
try { TimeUnit.MILLISECONDS.sleep(rand.nextInt(10000)); }
catch (InterruptedException e) {}
}
}
Upvotes: 0
Views: 88
Reputation: 638
What is happening here is you have 5 instances of CustomThread which each get a unique object, lock on it, and go to sleep. The other 5 threads get an object which is already in use, and so when their CustomThread attempts to lock on it, they must wait a max. of 10 seconds for the first thread to complete. At this point the second thread is able to lock on the object and it does.
Your use of Random means it's not literally the first 5 get a unique object and the second 5 don't but the basic idea is the same, the second CustomThread simply waits for the first to be done.
If you want to create a true deadlock you need the first thread which holds the lock to need something from the second thread which is waiting on the lock. It needs to be a circular dependency, Thread A waiting on Thread B while at the same time Thread B is waiting on Thread A. In your case you only have Thread B waiting on Thread A.
Found a question which may point you towards how to create a deadlock;
Upvotes: 1