JAVA EXAMPLES - SOLVING DEADLOCK

Similar documents
CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Multi-Threaded Programming Design CSCI 201 Principles of Software Development

Daemon thread, 7 Deadlock, 27

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Michele Van Dyne MUS 204B Concurrency Issues

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

CMSC 330: Organization of Programming Languages

CMSC 132: Object-Oriented Programming II

Concurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java ReentrantLock (Part 1)

CPSC 211. SOLUTIONS to PRACTICE EXERCISES II

Java Barrier Synchronizers: CyclicBarrier (Part 1)

G52CON: Concepts of Concurrency

Concurrency. Fundamentals of Computer Science

Timing ListOperations

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014

Internet Technology 2/7/2013

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Simpler, Faster, Better: Concurrency Utilities in JDK Software Version 5.0

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

COMP 322: Fundamentals of Parallel Programming

MODULE 6q - Exceptions

CS 351 Design of Large Programs Threads and Concurrency

CPSC 211. SOLUTIONS to PRACTICE EXERCISES II

Chapter 32 Multithreading and Parallel Programming

Part IV Other Systems: I Java Threads

Teaching predicates and invariants on shared data structures in concurrent programming

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Problems with Concurrency. February 19, 2014

i219 Software Design Methodology 12. Case study 1 Dining philosopher problem Kazuhiro Ogata (JAIST) Outline of lecture

C16b: Exception Handling

Threads Chate Patanothai

Concurrency and Java Programming

Warm up question. 2)Which of the following operators are defined on a half integer? Which of the following would it be useful to write as behaviors?

1 interface TemperatureSensor extends java.rmi.remote 2 { 3 public double gettemperature() throws java.rmi.remoteexception; 4 public void

CONCURRENT API AND PARALLEL PROGRAMMING

DUBLIN CITY UNIVERSITY

INFO Ass 4. Exercise 1

Concurrent Queues, Monitors, and the ABA problem. Companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit

Question Points Score Total 100

public class Shared0 { private static int x = 0, y = 0;

CS193k, Stanford Handout #8. Threads 3

Synchronized Methods of Old Versions of Java

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

F. Tip and M. Weintraub CONCURRENCY

CSC 1214: Object-Oriented Programming

Suggested solutions INF2440 Spring 2018 Written Exam

CPSC 211. SOLUTIONS to PRACTICE EXERCISES II

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

More thread safety and Concurrent collections. Nasser Giacaman CompSci 230: Software Design and Construction

PROGRAMMING FUNDAMENTALS

Java Barrier Synchronizers: CountDownLatch (Part 1)

JAVA. Lab 12 & 13: Multithreading

Principles of Software Construction: Concurrency, Part 1

Java Threads. COMP 585 Noteset #2 1

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

CONCURRENCY IN JAVA Course Parallel Computing

CSCI 201L Final Written Spring % of course grade

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

re-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M)


Vendor: Oracle. Exam Code: 1Z Exam Name: Java SE 8 Programmer. Version: Demo

Module - 4 Multi-Threaded Programming

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Nonblocking API. Introduction CHAPTER

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

Programming in Java

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

Nonblocking API. Introduction. Information About Reliability Support. Reliable Mode CHAPTER

Notes on access restrictions

Class, Variable, Constructor, Object, Method Questions

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

CS370 Operating Systems

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

JFokus Finding And Solving Java Deadlocks

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Timber: Time as a Basis for Embedded real-time systems. Andrew Black, Magnus Carlsson, Mark Jones, Dick Kieburtz, Johan Nordlander

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012

ECE462Exam3. 08:10-09:20AM, November 20, 2009

Principles of Software Construction: Concurrency, Part 2

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Synchronization synchronization.

CMSC 132: Object-Oriented Programming II. Threads in Java

7. MULTITHREDED PROGRAMMING

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

COMP 110 Programming Exercise: Simulation of the Game of Craps

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Computação I. Exercises. Leonardo Vanneschi NOVA IMS, Universidade Nova de Lisboa. Leonardo Vanneschi Computação I NOVA IMS

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

04-Java Multithreading

Transcription:

JAVA EXAMPLES - SOLVING DEADLOCK http://www.tutorialspoint.com/javaexamples/thread_deadlock.htm Copyright tutorialspoint.com Problem Description: How to solve deadlock using thread? Solution: Following example demonstrates how to solve deadlock using the concept of thread. import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*; public class DeadlockDetectingLock extends ReentrantLock { private static List deadlocklocksregistry = new ArrayList(); registerlock(deadlockdetectinglock ddl) { if (!deadlocklocksregistry.contains(ddl)) deadlocklocksregistry.add(ddl); unregisterlock(deadlockdetectinglock ddl) { if (deadlocklocksregistry.contains(ddl)) deadlocklocksregistry.remove(ddl); private List hardwaitingthreads = new ArrayList(); markashardwait(list l, Thread t) { if (!l.contains(t)) l.add(t); freeifhardwait(list l, Thread t) { if (l.contains(t)) l.remove(t); private static Iterator getalllocksowned(thread t) { DeadlockDetectingLock current; ArrayList results = new ArrayList(); Iterator itr = deadlocklocksregistry.iterator(); while (itr.hasnext()) { current = (DeadlockDetectingLock) itr.next(); if (current.getowner() == t) results.add(current); return results.iterator(); private static Iterator getallthreadshardwaiting(deadlockdetectinglock l) { return l.hardwaitingthreads.iterator(); private static synchronized boolean canthreadwaitonlock (Thread t,deadlockdetectinglock l) { Iterator locksowned = getalllocksowned(t); while (locksowned.hasnext()) { DeadlockDetectingLock current = (DeadlockDetectingLock) locksowned.next(); if (current == l) return false;

Iterator waitingthreads = getallthreadshardwaiting(current); while (waitingthreads.hasnext()) { Thread otherthread = (Thread) waitingthreads.next(); if (!canthreadwaitonlock(otherthread, l)) { return false; return true; public DeadlockDetectingLock() { this(false, false); public DeadlockDetectingLock(boolean fair) { this(fair, false); private boolean debugging; public DeadlockDetectingLock(boolean fair, boolean debug) { super(fair); debugging = debug; registerlock(this); public void lock() { if (isheldbycurrentthread()) { if (debugging) System.out.println("Already Own Lock"); super.lock(); return; if (canthreadwaitonlock(thread.currentthread(), this)) { if (debugging) System.out.println("Waiting For Lock"); super.lock(); if (debugging) System.out.println("Got New Lock"); else { throw new DeadlockDetectedException("DEADLOCK"); public void lockinterruptibly() throws InterruptedException { lock(); locks. public class DeadlockDetectingCondition implements Condition { Condition embedded; protected DeadlockDetectingCondition(ReentrantLock lock, Condition embedded) { this.embedded = embedded; Public void await() throws InterruptedException {

embedded.await(); public void awaituninterruptibly() { embedded.awaituninterruptibly(); public long awaitnanos(long nanostimeout) throws InterruptedException { return embedded.awaitnanos(nanostimeout); public boolean await(long time, TimeUnit unit) throws InterruptedException { return embedded.await(time, unit); public boolean awaituntil(date deadline) throws InterruptedException { return embedded.awaituntil(deadline); public void signal() { embedded.signal(); public void signalall() { embedded.signalall(); public Condition newcondition() { return new DeadlockDetectingCondition(this, super.newcondition());

private static Lock a = new DeadlockDetectingLock(false, true); private static Lock b = new DeadlockDetectingLock(false, true); private static Lock c = new DeadlockDetectingLock(false, true); private static Condition wa = a.newcondition(); private static Condition wb = b.newcondition(); private static Condition wc = c.newcondition(); private static void delayseconds(int seconds) { Thread.sleep(seconds * 1000); catch (InterruptedException ex) { private static void awaitseconds(condition c, int seconds) { c.await(seconds, TimeUnit.SECONDS); catch (InterruptedException ex) { private static void testone() { System.out.println("thread one grab a"); System.out.println("thread one grab b"); ).start(); System.out.println("thread two grab b"); System.out.println("thread two grab a"); ).start(); private static void testtwo() { System.out.println("thread one grab a"); delayseconds(2) ; System.out.println("thread one grab b"); ).start(); System.out.println("thread two grab b"); System.out.println("thread two grab c"); c.lock();

c.unlock(); ).start(); System.out.println("thread three grab c"); c.lock(); delayseconds(4); System.out.println("thread three grab a"); c.unlock(); ).start(); private static void testthree() { System.out.println("thread one grab b"); System.out.println("thread one grab a"); System.out.println("thread one waits on b"); awaitseconds(wb, 10); ).start(); delayseconds(1); System.out.println("thread two grab b"); System.out.println("thread two grab a"); c.unlock(); ).start(); public static void main(string args[]) { int test = 1; if (args.length > 0) test = Integer.parseInt(args[0]); switch (test) { case 1: testone(); break; case 2: testtwo(); break; case 3: testthree(); break; default: System.err.println("usage: java DeadlockDetectingLock [ test# ]"); delayseconds(60); System.out.println("--- End Program ---"); System.exit(0);

class DeadlockDetectedException extends RuntimeException { public DeadlockDetectedException(String s) { super(s); Result: The above code sample will produce the following result. thread one grab a Waiting For Lock Got New Lock thread two grab b Waiting For Lock Got New Lock thread one grab b Waiting For Lock thread two grab a Exception in thread "Thread-1" DeadlockDetectedException:DEADLOCK at DeadlockDetectingLock. lock(dealockdetectinglock.java:152) at java.lang.thread.run(thread.java:595)