Design a class which provides a lock if no deadlocks

Design a class which provides a lock only if there are no possible deadlocks.

Solution:
For our solution, we implement a wait / die deadlock prevention scheme.

	class MyThread extends Thread {
		long time;
		ArrayList<Resource> res = new ArrayList<Resource>();

		public ArrayList<Resource> getRes() {
			return res;
		}

		@Override
		public void run() {
			// Run infinitely
			time = System.currentTimeMillis();
			int count = 0;
			while (true) {
				if (count < 4) {
					if (Question.canAcquireResource(this, Question.r[count])) {
						res.add(Question.r[count]);
						count++;
						System.out.println("Resource: ["
								+ Question.r[count - 1].getId()
								+ "] acquired by thread: [" + this.getName()
								+ "]");
						try {
							sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				} else {
					this.stop();
				}
			}
		}

		public long getTime() {
			return time;
		}

		public void setRes(ArrayList<Resource> res) {
			this.res = res;
		}

		MyThread(String name) {
			super(name);
		}
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: