Deadlock Victim && && && && by Dr Heinz Kabutz The Java Specialists Newsletter

Size: px
Start display at page:

Download "Deadlock Victim && && && && by Dr Heinz Kabutz The Java Specialists Newsletter"

Transcription

1 1 Deadlock Victim by Dr Heinz Kabutz The Java Specialists Newsletter && && && && Olivier Croisier The Coder's Breakfast

2 2 You discover a race condition

3 3 Data is being corrupted

4 4 What ya gonna do?

5 5 Who ya gonna call?

6 6 Ghostbusters?

7 7 you do what we all do

8 8 you use synchronized

9 9 synchronized

10 9 synchronized

11 10 synchronized can be bad medicine

12 11 deadlock awaits you!

13 12

14 13 Deadlock Victim

15 14 Correctness fix can lead to liveness fault

16 15 lock ordering deadlock

17 16 at least two locks

18 17 and at least two threads

19 18 locked in different orders

20 19 can cause a deadly embrace

21 20 requires global analysis to fix

22 21 resource deadlocks

23 22 bounded queues

24 23 bounded thread pools

25 24 semaphores

26 25 class loaders

27 26 lost signals

28 27 The Drinking Philosophers

29 the Java Specialist Symposium in Crete

30 29 Symposium == sym + poto Literally - to drink together

31 30 our philosophers need two cups

32 31 they either want to drink or think

33 Table is ready, all philosophers are thinking

34 philosophers 5 wants to drink, takes right cup

35 Philosopher 5 is now drinking with both cups

36 philosophers 3 wants to drink, takes right cup

37 Philosopher 3 is now drinking with both cups

38 philosophers 2 wants to drink, takes right cup

39 Philosopher 3 finished drinking, returns right cup

40 Philosopher 2 is now drinking with both cups

41 Philosopher 3 returns Left cup

42 41 philosophers can get stuck

43 42 if they all pick up the right cup

44 A deadlock can easily happen with this design

45 Philosopher 5 wants to drink, takes right cup

46 Philosopher 1 wants to drink, takes right cup

47 Philosopher 2 wants to drink, takes right cup

48 Philosopher 3 wants to drink, takes right cup

49 Philosopher 4 wants to drink, takes right cup

50 Deadlock!

51 they will all stay thirsty

52 this is a deadly embrace

53 52 this can be detected automatically

54 53 search the graph of call stacks

55 54 and look for circular dependencies

56 55 ThreadMXBean does that for us

57 56 simple deadlocks are quickly found

58 57 but what do you DO with them?

59 58 what will the dog do with the car if he ever catches it?

60 59 databases choose deadlock victim

61 60 but what does Java do?

62 61 it should probably throw an Error

63 62 but the threads simply hang up

64 63 it is best to avoid causing them!

65 64 global order of locks in program

66 public class LeftRightDeadlock { private final Object left = new Object(); private final Object right = new Object(); public void leftright() { synchronized (left) { synchronized (right) { dosomething(); } } } public void rightleft() { synchronized (right) { synchronized (left) { dosomethingelse(); } } } } 65

67 Interleaving causes deadlock lock left trying to lock right A leftright() BLOCKED lock right trying to lock left B rightleft() BLOCKED 66

68 67 we define a fixed global order

69 68 e.g. left before right

70 69 deadlock is solved! public void rightleft() { synchronized (left) { synchronized (right) { dosomethingelse(); } } }

71 70 our drinking philosophers

72 71 each cup gets a unique number

73 72 lock the highest number cup first

74 73 then lock the lower number cup

75 74 drink

76 75 unlock lower order cup

77 76 unlock higher order cup

78 77 think

79 Global Lock ordering We start with all the philosophers thinking

80 Philosopher 5 takes cup 5 Cup 5 has higher number 1 Remember our rule!

81 Philosopher 1 takes cup 2 Must take the cup with the higher number first 1 2 In this case cup

82 Philosopher 2 takes cup

83 Philosopher 3 takes cup

84 Philosopher 1 takes cup 1 - Drinking

85 Philosopher 1 returns Cup 1 Cups are returned in the opposite order to what they are acquired

86 Philosopher 5 takes cup 1 - Drinking

87 Philosopher 5 returns cup

88 Philosopher 1 returns cup

89 Philosopher 2 takes cup 2 - Drinking

90 Philosopher 5 returns cup

91 Philosopher 4 takes cup

92 Philosopher 2 returns cup

93 Philosopher 2 returns cup

94 Philosopher 3 takes cup 3 - Drinking

95 Philosopher 3 Returns cup

96 Philosopher 3 Returns cup

97 Philosopher 4 takes cup 4 - Drinking

98 Philosopher 4 Returns cup

99 Philosopher 4 Returns cup

100 99 sorting locks by property is easy

101 100 e.g. account IBAN number

102 101 or employee number

103 102 or some other characteristic

104 103 maybe even System.identityHashCode()

105 104 use "open calls"

106 105 Vector synchronizes writeobject() private synchronized void writeobject(objectoutputstream s) throws IOException { s.defaultwriteobject(); }

107 106 synchronized writeobject() is invoking s.defaultwriteobject() private synchronized void writeobject(objectoutputstream s) throws IOException { s.defaultwriteobject(); }

108 107 this is not an "open call" private synchronized void writeobject(objectoutputstream s) throws IOException { s.defaultwriteobject(); }

109 108 but can it cause problems? private synchronized void writeobject(objectoutputstream s) throws IOException { s.defaultwriteobject(); }

110 109 yes it can! private synchronized void writeobject(objectoutputstream s) throws IOException { s.defaultwriteobject(); }

111 110 serialize both vectors at same time Vector v1 = new Vector(); Vector v2 = new Vector(); v1.add(v2); v2.add(v1);

112 111 this could happen with nested data structures

113 112 it happened to an IBM client

114 private void writeobject(objectoutputstream stream) throws IOException { Vector<E> cloned = null; // this specially fix is for a special dead-lock in customer // program: two vectors refer each other may meet dead-lock in // synchronized serialization. Refer CMVC synchronized (this) { try { cloned = (Vector<E>) super.clone(); cloned.elementdata = elementdata.clone(); } catch (CloneNotSupportedException e) { // no deep clone, ignore the exception } } cloned.writeobjectimpl(stream); } private void writeobjectimpl(objectoutputstream stream) throws IOException { stream.defaultwriteobject(); } 113

115 114 Java 7 uses an "open call" private void writeobject(objectoutputstream s) throws IOException { final ObjectOutputStream.PutField fields = s.putfields(); final Object[] data; synchronized (this) { fields.put("capacityincrement", capacityincrement); fields.put("elementcount", elementcount); data = elementdata.clone(); } fields.put("elementdata", data); s.writefields(); }

116 More synchronized writeobject()s File StringBuffer Throwable URL Hashtable and others 115

117 116 we have seen the deadly embrace

118 117 are there other deadlocks?

119 118 semaphore deadlocks

120 119 Bounded DB Connection Pools For example, say you have two DB connection pools Some tasks might require connections to both databases Thus thread A might hold semaphore for D1 and wait for D2, whereas thread B might hold semaphore for D2 and be waiting for D1

121 120 public class DatabasePool { private final Semaphore connections; public DatabasePool(int connections) { this.connections = new Semaphore(connections); } public void connect() { connections.acquireuninterruptibly(); System.out.println("DatabasePool.connect"); } } public void disconnect() { System.out.println("DatabasePool.disconnect"); connections.release(); }

122 121 ThreadMXBean does not show this as a deadlock!

123 122 JVM does not detect this deadlock

124 122 JVM does not detect this deadlock

125 123 Avoiding and diagnosing deadlocks Avoiding Liveness Hazards

126 Avoiding and diagnosing deadlocks You cannot get a lock-ordering deadlock with a single lock Easiest way to avoid deadlocks But not always practical 124

127 Avoiding and diagnosing deadlocks For multiple locks we need to define a lock order specify and document possible lock sequences Identify where multiple locks could be acquired Do a global analysis to ensure that lock ordering is consistent This can be extremely difficult in large programs 125

128 126 Use open calls whenever possible

129 127 Unit Testing for lock ordering deadlocks Code typically has to be called many times before a deadlock happens How many times do you need to call it to prove that there is no deadlock? Nondeterministic unit tests are bad - they should either always pass or always fail

130 Testing the Bank In the transfermoney() method, a deadlock occurs if after the first lock is granted, the first thread is swapped out and another thread requests the second lock public class Bank { public boolean transfermoney(account from, Account to, Amount amount) { synchronized (from) { // if thread is swapped out here, we can end up with a deadlock synchronized (to) { return doactualtransfer(from, to, amount); } } } } 128

131 129 We can force the context switch

132 130 simply add a sleep after first lock

133 Adding a sleep to cause deadlocks public class Bank { public boolean transfermoney(account from, Account to, Amount amount) { synchronized (from) { sleepawhilefortesting(); synchronized (to) { return doactualtransfer(from, to, amount); } } } protected void sleepawhilefortesting() {} } 131

134 In our unit test we use a SlowBank public class SlowBank extends Bank { private final long timeout; private final TimeUnit unit; public SlowBank(long timeout, TimeUnit unit) { this.timeout = timeout; this.unit = unit; } protected void sleepawhilefortesting() { try { unit.sleep(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } 132

135 133 Won't this cause problems in production?

136 134 In production we only use Bank

137 135 HotSpot will optimize away empty sleepawhilefortesting()

138 136 it is thus a zero cost

139 137 as long as SlowBank is never used

140 138 How can you verify the lockordering deadlock?

141 139 CTRL+Break, jstack, kill -3, jconsole, etc.

142 140 but that won't be a good unit test

143 141 Better via Java's ThreadMXBean

144 142 ThreadMXBean Get instance with ManagementFactory.getThreadMXBean() findmonitordeadlockedthreads() Includes only "monitor" locks, i.e. synchronized Only way to find deadlocks in Java 5

145 143 ThreadMXBean Better is finddeadlockedthreads() Includes "monitor" and "owned" (Java 5) locks Preferred method to test for deadlocks But, does not find deadlocks between semaphores See

146 144 public class BankDeadlockTest { private final static ThreadMXBean tmb = ManagementFactory.getThreadMXBean(); private boolean isthreaddeadlocked(long tid) { long[] ids = tmb.finddeadlockedthreads(); if (ids == null) return false; for (long id : ids) { if (id == tid) return true; } return false; }

147 145 private void checkthatthreadterminates(thread thread) throws InterruptedException { for (int i = 0; i < 2000; i++) { thread.join(50); if (!thread.isalive()) return; if (isthreaddeadlocked(thread.getid())) { fail("deadlock detected!"); } } fail(thread + " did not terminate in time"); }

148 @Test public void testfortransferdeadlock() throws InterruptedException { final Account alpha = new Account(new Amount(1000)); final Account ubs = new Account(new Amount( )); final Bank bank = new SlowBank(100, TimeUnit.MILLISECONDS); Thread alphatoubs = new Thread("alphaToUbs") { public void run() { bank.transfermoney(alpha, ubs, new Amount(100)); } }; Thread ubstoalpha = new Thread("ubsToAlpha") { public void run() { bank.transfermoney(ubs, alpha, new Amount(100)); } }; alphatoubs.start(); ubstoalpha.start(); } } checkthatthreadterminates(alphatoubs); 146

149 Output with broken transfermoney() method We see the deadlock within about 100 milliseconds junit.framework.assertionfailederror: Deadlock detected! at BankDeadlockTest.checkThatThreadTerminates(BankDeadlockTest.java:20) at BankDeadlockTest.testForTransferDeadlock(BankDeadlockTest.java:55) 147

150 Output with broken transfermoney() method If we fix the transfermoney() method, it also completes within about 100 milliseconds This is the time that we are sleeping for testing purposes Remember that the empty sleepawhilefortesting() method will be optimized away by HotSpot 148

151 149 Timed lock attempts Another technique for solving deadlocks is to use the timed trylock() method of explicit Java locks

152 150 However, if trylock() fails it may be

153 151 a deadlock

154 152 or some thread taking a long time

155 153 or a thread in an infinite loop

156 154 But ThreadMXBean shows it as deadlocked

157 155 even if it is a temporary condition

158 156 The JVM has support for trylock with synchronized

159 157 but it is hidden away

160 158 So here it is

161 159

162 160 Told you it was hidden!

163 161 It is hidden for a good reason

164 162 if you need trylock functionality

165 163 rather use explicit locks (ReentrantLock)

166 164 trylock with synchronized Technically possible in Sun JVM using Unsafe.getUnsafe().tryMonitorEnter(monitor) Unsafe.getUnsafe().monitorExit(monitor)

167 165 Deadlock analysis with thread dumps

168 Deadlock analysis with thread dumps We can also cause a thread dump in many ways: Ctrl+Break on Windows or Ctrl-\ on Unix Invoking "kill -3" on the process id Calling jstack on the process id Only shows deadlocks since Java 6 Intrinsic locks show more information of where they were acquired 166

169 167 Can a deadlock be resolved?

170 168 NO with synchronized

171 169 YES with ReentrantLock

172 170 synchronized() goes into BLOCKED state

173 171 ReentrantLock.lock() goes into WAITING state

174 172 We can write a DealockArbitrator

175 173 This stops one of the threads with a DeadlockVictimError

176 Our special Error for deadlocks public class DeadlockVictimError extends Error { private final Thread victim; public DeadlockVictimError(Thread victim) { super("deadlock victim: " + victim); this.victim = victim; } } public Thread getvictim() { return victim; } 174

177 public class DeadlockArbitrator { private static final ThreadMXBean tmb = ManagementFactory.getThreadMXBean(); public boolean tryresolvedeadlock( int attempts, long timeout, TimeUnit unit) throws InterruptedException { for (int i = 0; i < attempts; i++) { long[] ids = tmb.finddeadlockedthreads(); if (ids == null) return true; Thread t = findthread(ids[i % ids.length]); if (t == null) throw new IllegalStateException("Could not find thread"); t.stop(new DeadlockVictimError(t)); unit.sleep(timeout); } return false; } 175

178 finding threads by id is tricky public boolean tryresolvedeadlock() throws InterruptedException { return tryresolvedeadlock(3, 1, TimeUnit.SECONDS); } } private Thread findthread(long id) { for (Thread thread : Thread.getAllStackTraces().keySet()) { if (thread.getid() == id) return thread; } return null; } 176

179 Applicability of DeadlockArbitrator Only use in extreme circumstances Code that is outside your control and that deadlocks Where you cannot prevent the deadlock Remember, it only works with ReentrantLock 177

180 178 Deadlock Victim Questions? by Dr Heinz Kabutz The Java Specialists Newsletter && && && && Olivier Croisier The Coder's Breakfast

JFokus Finding And Solving Java Deadlocks

JFokus Finding And Solving Java Deadlocks JFokus 03 - Finding And Solving Java Deadlocks Dr Heinz Kabutz JFokus 03 - Finding and Solving Java Deadlocks Heinz Kabutz German from Cape Town, now lives in Chania PhD Computer Science from University

More information

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

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

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

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

More information

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

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

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

COMP 150-CCP Concurrent Programming. Lecture 12: Deadlock. Dr. Richard S. Hall

COMP 150-CCP Concurrent Programming. Lecture 12: Deadlock. Dr. Richard S. Hall COMP 150-CCP Concurrent Programming Lecture 12: Deadlock Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 28, 2008 Scenario Process 1 gets the lock for object A and wants to lock

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

Concurrency in Java Prof. Stephen A. Edwards

Concurrency in Java Prof. Stephen A. Edwards Concurrency in Java Prof. Stephen A. Edwards The Java Language Developed by James Gosling et al. at Sun Microsystems in the early 1990s Originally called Oak, first intended application was as an OS for

More information

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

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Threads block when they can t get that lock Wanna have your threads stall? Go ahead, synchronize it all The antidote to this liveness pitfall? Keeping

More information

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Wait / Notify / NotifyAll Optimistic Retries Composition Follow-up (the risk I mentioned) ReentrantLock, Wait, Notify, NotifyAll Some

More information

F. Tip and M. Weintraub CONCURRENCY

F. Tip and M. Weintraub CONCURRENCY F. Tip and M. Weintraub CONCURRENCY SHARED-MEMORY CONCURRENCY threads execute concurrently threads communicate values via shared memory synchronization using locks 2 PITFALLS data races atomicity violations

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 11 Synchronisation in Java II Natasha Alechina School of Computer Science nza@cs.nott.ac.uk Outline of this lecture Mutual exclusion in Java continued (next lecture:

More information

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

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

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 Threads and Locks, Part 2 CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 1 Goals Cover the material presented in Chapter 2 of our concurrency textbook In particular, selected material

More information

PROCESS SYNCHRONIZATION

PROCESS SYNCHRONIZATION PROCESS SYNCHRONIZATION Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization

More information

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

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

THREADS AND CONCURRENCY

THREADS AND CONCURRENCY THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on

More information

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

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer. CMSC 330: Organization of Programming Languages Threads Computation Abstractions t1 t2 t1 t3 t2 t1 p1 p2 p3 p4 CPU 1 CPU 2 A computer t4 t5 Processes (e.g., JVM s) Threads CMSC 330 2 Processes vs. Threads

More information

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem Mack Joyner and Zoran Budimlić {mjoyner, zoran}@rice.edu http://comp322.rice.edu

More information

THREADS & CONCURRENCY

THREADS & CONCURRENCY 4/26/16 Announcements BRING YOUR CORNELL ID TO THE PRELIM. 2 You need it to get in THREADS & CONCURRENCY Prelim 2 is next Tonight BRING YOUR CORNELL ID! A7 is due Thursday. Our Heap.java: on Piazza (A7

More information

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 9: Readers-Writers and Language Support for Synchronization 9.1.2 Constraints 1. Readers can access database

More information

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a. Let s start writing programs that do more than one thing at at a. Threads, Concurrency,

More information

Threads, Concurrency, and Parallelism

Threads, Concurrency, and Parallelism Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start

More information

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy Operating Systems Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. AL-AZHAR University Website : eaymanelshenawy.wordpress.com Email : eaymanelshenawy@yahoo.com Reference

More information

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

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand

More information

CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable)

CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable) CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable) Past & Present Have looked at two constraints: Mutual exclusion constraint between two events is a requirement that

More information

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

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark Multithreading Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@stll.au..dk Submission & Peer feedback peergrade.io/join AJJ452 What is going on here? Multithreading Threads

More information

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

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory

More information

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico. Java Monitors Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 19, 2010 Monteiro, Costa (DEI / IST) Parallel and Distributed Computing

More information

The Secrets of Concurrency

The Secrets of Concurrency The Secrets of Concurrency 1 The Secrets of Concurrency Dr Heinz M. Kabutz 2007 Heinz Kabutz All Rights Reserved The Secrets of Concurrency 2 The Secrets of Concurrency In this talk you will learn the

More information

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing

More information

Java 8 From Smile To Tears: Emotional Stampedlock

Java 8 From Smile To Tears: Emotional Stampedlock !1 Java 8 From Smile To Tears: Emotional Stampedlock Dr Heinz M. Kabutz Last updated 2014-03-23 !2 Heinz Kabutz l Author of The Java Specialists' Newsletter Articles about advanced core Java programming

More information

Problems with Concurrency. February 19, 2014

Problems with Concurrency. February 19, 2014 with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Object Oriented Programming and Design in Java. Session 18 Instructor: Bert Huang

Object Oriented Programming and Design in Java. Session 18 Instructor: Bert Huang Object Oriented Programming and Design in Java Session 18 Instructor: Bert Huang Announcements Homework 4 due Mon. Apr. 19 No multithreading in programming part Final Exam Monday May 10, 9 AM - noon, 173

More information

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems More Synchronization; Concurrency in Java CS 475, Spring 2018 Concurrent & Distributed Systems Review: Semaphores Synchronization tool that provides more sophisticated ways (than Mutex locks) for process

More information

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

Concurrency in Object Oriented

Concurrency in Object Oriented Concurrency in Object Oriented Programs 5 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter 1 Outline Deadlocks Dining Philosophers Lock Ordering Reducing Lock Granularity

More information

The Secrets of Concurrency

The Secrets of Concurrency The Secrets of Concurrency Dr Heinz M. Kabutz The Java Specialists Newsletter http://www.javaspecialists.eu 2008 Heinz Kabutz All Rights Reserved The Secrets of Concurrency In this talk you will learn

More information

Only one thread can own a specific monitor

Only one thread can own a specific monitor Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification

More information

Synchronized Methods of Old Versions of Java

Synchronized Methods of Old Versions of Java Administrivia Assignment #4 is out Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in labs next week for a demo time In case you hadn t noticed Classes end Thursday April 15

More information

Java ReentrantLock (Part 1)

Java ReentrantLock (Part 1) Java ReentrantLock (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017 CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution

More information

DUBLIN CITY UNIVERSITY

DUBLIN CITY UNIVERSITY DUBLIN CITY UNIVERSITY SEMESTER ONE RESIT EXAMINATIONS 2012 MODULE TITLE: MODULE CODE: COURSE: Concurrent Programming CA463/CA463D BSc. in Computer Applications (Software Engineering Stream), Study Abroad

More information

The Secrets of Concurrency. The Secrets of Concurrency

The Secrets of Concurrency. The Secrets of Concurrency The Secrets of Concurrency Dr Heinz M. Kabutz 1 In this talk you will learn the most important secrets to writing multi threaded Java code 2 Background Heinz Kabutz German Dutch South African married to

More information

Animation Part 2: MoveableShape interface & Multithreading

Animation Part 2: MoveableShape interface & Multithreading Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply

More information

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

Info 408 Distributed Applications Programming Exercise sheet nb. 4

Info 408 Distributed Applications Programming Exercise sheet nb. 4 Lebanese University Info 408 Faculty of Science 2017-2018 Section I 1 Custom Connections Info 408 Distributed Applications Programming Exercise sheet nb. 4 When accessing a server represented by an RMI

More information

The New Java Technology Memory Model

The New Java Technology Memory Model The New Java Technology Memory Model java.sun.com/javaone/sf Jeremy Manson and William Pugh http://www.cs.umd.edu/~pugh 1 Audience Assume you are familiar with basics of Java technology-based threads (

More information

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

More information

Deadlock CS 241. March 19, University of Illinois

Deadlock CS 241. March 19, University of Illinois Deadlock CS 241 March 19, 2014 University of Illinois Slides adapted in part from material accompanying Bryant & O Hallaron, Computer Systems: A Programmer's Perspective, 2/E 1 The Dining Philosophers

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

Reintroduction to Concurrency

Reintroduction to Concurrency Reintroduction to Concurrency The execution of a concurrent program consists of multiple processes active at the same time. 9/25/14 7 Dining philosophers problem Each philosopher spends some time thinking

More information

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

Concurrency, Thread. Dongkun Shin, SKKU

Concurrency, Thread. Dongkun Shin, SKKU Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point

More information

Threads & Concurrency

Threads & Concurrency 2 Due date of A7 Due d About A5-A6 We have changed the due date of A7 Friday, 28 April. Threads & Concurrency But the last date to submit A7 remains the same: 29 April. We make the last date be 29 April

More information

CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019

CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019 CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion Ruth Anderson Winter 2019 Toward sharing resources (memory) So far, we have been studying parallel algorithms

More information

Concurrent Programming. Concurrent Programming. Today. Comp 104: Operating Systems Concepts 05/01/2017. Concurrent Programming & Threads

Concurrent Programming. Concurrent Programming. Today. Comp 104: Operating Systems Concepts 05/01/2017. Concurrent Programming & Threads Comp 104: Operating Systems Concepts Concurrent Programming & Threads Today Introduction to Concurrent Programming Threads Java Threads and Realisation 1 2 Concurrent Programming Consider a program that

More information

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 30: Java Synchronizers, Dining Philosophers Problem Vivek Sarkar, Shams Imam Department of Computer Science, Rice University Contact email: vsarkar@rice.edu,

More information

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

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming. Lecture 07: Advanced Thread programming Software System Components 2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Recap How to deal with race condition in Java Using synchronised

More information

generate-jvm-report shows the threads, classes, memory, and loggers for a given target instance. Name Synopsis

generate-jvm-report shows the threads, classes, memory, and loggers for a given target instance. Name Synopsis Name Synopsis Description Options generate-jvm-report shows the threads, classes, memory, and loggers for a given target instance. generate-jvm-report [--help] [ --type =summary memory class thread log]

More information

Dealing with Issues for Interprocess Communication

Dealing with Issues for Interprocess Communication Dealing with Issues for Interprocess Communication Ref Section 2.3 Tanenbaum 7.1 Overview Processes frequently need to communicate with other processes. In a shell pipe the o/p of one process is passed

More information

Part IV Other Systems: I Java Threads

Part IV Other Systems: I Java Threads Part IV Other Systems: I Java Threads Spring 2019 C is quirky, flawed, and an enormous success. 1 Dennis M. Ritchie Java Threads: 1/6 Java has two ways to create threads: Create a new class derived from

More information

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples

More information

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

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization

More information

Introduction to Concurrent Software Systems. CSCI 5828: Foundations of Software Engineering Lecture 08 09/17/2015

Introduction to Concurrent Software Systems. CSCI 5828: Foundations of Software Engineering Lecture 08 09/17/2015 Introduction to Concurrent Software Systems CSCI 5828: Foundations of Software Engineering Lecture 08 09/17/2015 1 Goals Present an overview of concurrency in software systems Review the benefits and challenges

More information

BlockingArrayQueue.java. Page 1

BlockingArrayQueue.java. Page 1 1 //BlockingArrayQueue.java 2 //Template blocking queue class, implemented with emulated circular array. 3 //Programmer: Randy Miller 4 //Last modification: April 13, 2015 5 6 7 8 import java.util.arraylist;

More information

CST242 Concurrency Page 1

CST242 Concurrency Page 1 CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Dr Heinz M. Kabutz. The Secrets of Concurrency. The Java Specialists Newsletter.

Dr Heinz M. Kabutz. The Secrets of Concurrency. The Java Specialists Newsletter. The Secrets of Concurrency Dr Heinz M. Kabutz The Java Specialists Newsletter http://www.javaspecialists.eu 2007 Heinz Max Kabutz All Rights Reserved The Secrets of Concurrency In this talk you will learn

More information

Synchronization Spinlocks - Semaphores

Synchronization Spinlocks - Semaphores CS 4410 Operating Systems Synchronization Spinlocks - Semaphores Summer 2013 Cornell University 1 Today How can I synchronize the execution of multiple threads of the same process? Example Race condition

More information

THREADS & CONCURRENCY

THREADS & CONCURRENCY 27/04/2018 Sorry for the delay in getting slides for today 2 Another reason for the delay: Yesterday: 63 posts on the course Piazza yesterday. A7: If you received 100 for correctness (perhaps minus a late

More information

Threads and Java Memory Model

Threads and Java Memory Model Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing

More information

Java Programming Lecture 23

Java Programming Lecture 23 Java Programming Lecture 23 Alice E. Fischer April 19, 2012 Alice E. Fischer () Java Programming - L23... 1/20 April 19, 2012 1 / 20 Outline 1 Thread Concepts Definition and Purpose 2 Java Threads Creation

More information

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency + Lecture 25: Concurrency + Today n Reading n P&C Section 6 n Objectives n Concurrency 1 + Concurrency n Correctly and efficiently controlling access by multiple threads to shared resources n Programming

More information

Introduction to Concurrent Software Systems. CSCI 5828: Foundations of Software Engineering Lecture 12 09/29/2016

Introduction to Concurrent Software Systems. CSCI 5828: Foundations of Software Engineering Lecture 12 09/29/2016 Introduction to Concurrent Software Systems CSCI 5828: Foundations of Software Engineering Lecture 12 09/29/2016 1 Goals Present an overview of concurrency in software systems Review the benefits and challenges

More information

Monitors; Software Transactional Memory

Monitors; Software Transactional Memory Monitors; Software Transactional Memory Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico March 17, 2016 CPD (DEI / IST) Parallel and Distributed

More information

The Secrets of Concurrency

The Secrets of Concurrency The Secrets of Concurrency 1 The Secrets of Concurrency Dr Heinz M. Kabutz heinz@javaspecialists.eu 2007-2009 Heinz Kabutz All Rights Reserved The Secrets of Concurrency 2 Thanks Shopmedia! Thank you for

More information

Models of concurrency & synchronization algorithms

Models of concurrency & synchronization algorithms Models of concurrency & synchronization algorithms Lecture 3 of TDA383/DIT390 (Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2016/2017 Today s menu

More information

Threads & Concurrency

Threads & Concurrency Threads & Concurrency Lecture 24 CS2110 Spring 2017 Due date of A7 Due d About A5-A6 2 We have changed the due date of A7 Friday, 28 April. But the last date to submit A7 remains the same: 29 April. We

More information

RACE CONDITIONS AND SYNCHRONIZATION

RACE CONDITIONS AND SYNCHRONIZATION RACE CONDITIONS AND SYNCHRONIZATION Lecture 21 CS2110 Fall 2010 Reminder 2 A race condition arises if two threads try and share some data One updates it and the other reads it, or both update the data

More information

Multi-threading in Java. Jeff HUANG

Multi-threading in Java. Jeff HUANG Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading

More information

The Secrets of Concurrency

The Secrets of Concurrency 1 The Secrets of Concurrency Dr Heinz M. Kabutz www.javaspecialists.eu Last updated: 27-05-2015 2007-2015 Heinz Kabutz All Rights Reserved 2 Heinz Kabutz l Brief Biography German-Dutch-South-African-Greek

More information

Threads and Parallelism in Java

Threads and Parallelism in Java Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program

More information

The Secrets of Concurrency

The Secrets of Concurrency 2007 Heinz Max Kabutz All Rights Reserved The Secrets of Concurrency Dr Heinz M. Kabutz The Java Specialists Newsletter http://www.javaspecialists.eu The Secrets of Concurrency Make those multi-cores earn

More information

Ch 9: Control flow. Sequencers. Jumps. Jumps

Ch 9: Control flow. Sequencers. Jumps. Jumps Ch 9: Control flow Sequencers We will study a number of alternatives traditional sequencers: sequential conditional iterative jumps, low-level sequencers to transfer control escapes, sequencers to transfer

More information

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2019 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information

Deadlock. Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1

Deadlock. Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1 Deadlock Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1 Recap: Synchronization Race condition A situation when two or more threads read and write shared

More information

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption

More information

JAVA EXAMPLES - SOLVING DEADLOCK

JAVA EXAMPLES - SOLVING DEADLOCK 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

More information

Deadlock. Only one process can use the resource at a time but once it s done it can give it back for use by another process.

Deadlock. Only one process can use the resource at a time but once it s done it can give it back for use by another process. Deadlock A set of processes is deadlocked if each process in the set is waiting for an event that can be caused by another process in the set. The events that we are mainly concerned with are resource

More information

Faculty of Computers & Information Computer Science Department

Faculty of Computers & Information Computer Science Department Cairo University Faculty of Computers & Information Computer Science Department Theoretical Part 1. Introduction to Critical Section Problem Critical section is a segment of code, in which the process

More information

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010 CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion Tyler Robison Summer 2010 1 Toward sharing resources (memory) So far we ve looked at parallel algorithms using fork-join

More information