Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Sample program in java for Deadlock

package concurrency;
public class DeadLock {
    public static void main(String[] args) {
        JavaFile firstFile = new JavaFile("file1");
        JavaFile secondFile = new JavaFile("file2");
        JavaCoder firstCode = new JavaCoder(firstFile, secondFile, "first coder:");
        JavaCoder secondCoder = new JavaCoder(secondFile, firstFile, "second coder:");
        firstCode.start();
        secondCoder.start();
    }
}
class JavaCoder extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().getName() + "trying to checkin " + firstfile);
        this.firstfile.checkIn(this.secondfile);
    }
    private JavaFile secondfile;
    private JavaFile firstfile;
    JavaCoder(JavaFile firstFile, JavaFile secondFile, String name) {
        super(name);
        this.firstfile = firstFile;
        this.secondfile = secondFile;
    }
};
class JavaFile {
    private String name;
    JavaFile(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return this.name;
    }
    public synchronized void checkIn(JavaFile otherFile) {
        System.out.println(Thread.currentThread().getName() + "in check-in " + this);
        otherFile.checkOut();
        System.out.println(Thread.currentThread().getName() + "completing check-in " + this);
    }
    public synchronized void checkOut() {
        System.out.println(Thread.currentThread().getName() + "in check-out " + this);
        while (true) {
        }
    }
};
 
Sample Output
first coder:trying to checkin file1
first coder:in check-in file1
first coder:in check-out file2
second coder:trying to checkin file2 ( This is the dead lock , second coder is trying to checkin file 2 which is locked by first coder for check-out)

No comments:

Post a Comment

Search 24 Bytes

Loading...