suggest me any real time situations in which i'm supposed to create multiple threads,and then introduce a deadlock situation.this is kind of a project!!! can u ppl help to make the application more interestin with some real time situation...
You can use the producer-consumer algorithm to demonstrate multi-threading.
Report generator Scenario would be, data per report is inserted into a queue for further processing by one service (the producer). The report processor service (the consumer) takes data for a report from the queue and processes them one report at a time. There can be 5 diferent instances of report processor service. All of them consume reports from a single queue (this is where you might need to introduce locks on the queue, etc).
This will cause a deadlock:
public static void main(String[] args)
{
final Object object1 = new Object();
final Object object2 = new Object();
Thread thread1 = new Thread(
new Runnable()
{
public void run()
{
try
{
//**** Lock on object1 first ****
synchronized(object1)
{
Thread.sleep(1000);
//**** Lock on object2 second ****
synchronized(object2)
{
System.out.println("Should never get here.");
}
}
}
catch (InterruptedException e)
{
System.out.println("Thread interupted.");
}
}
}
);
Thread thread2 = new Thread(
new Runnable()
{
public void run()
{
try
{
//**** Lock on object2 first ****
synchronized(object2)
{
Thread.sleep(1000);
//**** Lock on object1 second ****
synchronized(object1)
{
System.out.println("Should never get here.");
}
}
}
catch (InterruptedException e)
{
System.out.println("Thread interupted.");
}
}
}
);
thread1.start();
thread2.start();
}
Basically you've got 2 threads competing for locks on the same objects. Thread 1 gets the lock on object1
while thread 2 gets a lock on object2
, each then tries to get a lock on the other object and you've got a deadlock because another thread already has the lock.
You can also deadlock with a fixed size thread pool:
final ExecutorService exec = Executors.newFixedThreadPool(1);
exec.submit(new Runnable() {
public void run() {
Future<?> f = exec.submit(new Runnable() {
public void run() {
}
});
try { f.get(); } catch (Exception ex) { }
}
});