Concurrency in Object Oriented
|
|
- Kelly Carroll
- 5 years ago
- Views:
Transcription
1 Concurrency in Object Oriented Programs 5 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter 1
2 Outline Deadlocks Dining Philosophers Lock Ordering Reducing Lock Granularity Open calls Use of polling and timeouts Atomic acquisition of multiple locks Semaphores Lock Striping 2
3 Deadlocks Livenessis a concurrent application's ability to execute in a timely manner tension between safety and liveness Deadlock occurs in a program when all its constituent threads are blocked each thread was blocked waiting for a resource held by the other Java applications do not recover from deadlock 3
4 Four Conditions for Deadlock ref Coffman, Elphick and Shoshani(1971) Serially reusable resources a resource is either assigned to one thread or it is available No preemption only a thread holding a resource may release it Incremental acquisition threads already holding resources may request new resources Wait-for cycle two or more threads form a circular chain 4
5 Preventing Deadlock Removing mutual exclusion no thread may have exclusive access to a resource but then it is difficult to maintain safety See non-blocking synchronization algorithms Allow preemption In Java, applications need to repeatedly check for interrupted status Can be difficult to maintain consistent state Remove incremental acquisition a thread acquires all the resources it will need in one hit Avoid circular wait use a partial order on resources e.g. memory addresss/ object hashcodes manage resources hierarchically Last 2 points will be considered in these slides 5
6 Dining Philosophers Problem Dijkstra, 1968 Five philosophers sit around a circular table. Each philosopher spends his life alternately thinking and eating. In the centre of the table is a large bowl of spaghetti. A philosopher needs two forks to eat a helping of spaghetti One fork is placed between each pair of philosophers and they agree to only use the fork to his immediate right and left
7 Dining Philosophers Problem A demonstration of deadlock 7
8 A Trivial Deadlock Example 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(); 8
9 A Trivial Deadlock Example Unlucky Timing in LeftRightDeadlock A program will be free of deadlocks if all threads acquire the locks they need in a fixed global order 9
10 DeadlockProne? public void transfermoney(account fromaccount, Account toaccount, DollarAmountamount) throws InsufficientFundsException{ synchronized (fromaccount){ synchronized (toaccount){ if (fromaccount.getbalance().compareto(amount) < 0) else { fromaccount.debit(amount); toaccount.credit(amount); throw new InsufficientFundsException(); Safety from race conditions requires some form of locking on both accounts, as shown, so that transfer will not result in funds being lost 10
11 Dynamic Lock-Ordering Deadlock public void transfermoney(account fromaccount, Account toaccount, DollarAmountamount) throws InsufficientFundsException{ synchronized (fromaccount){ synchronized (toaccount){ if (fromaccount.getbalance().compareto(amount) < 0) else { fromaccount.debit(amount); toaccount.credit(amount); throw new InsufficientFundsException(); Deadlock can arise from concurrent calls: transfermoney(myaccount, youraccount, 10); transfermoney(youraccount, myaccount, 20); 11
12 Deadlocks in Java The JVM is not very helpful in resolving deadlocks When a set of Java threads deadlock, that's the end of the game Deadlocks rarely manifest themselves immediately The fact that a class has a potential deadlock doesn't mean that it ever will deadlock Avoiding deadlocks is hard in Java! 12
13 Avoiding Deadlocks The hardest problem in concurrent programming A program will be free of deadlocks if all threads acquire the locks in a fixed global order asymmetry (Dining Philosophers Problem) can use hash code value to order locks Deadlock may be caused by coarse-grained locking shrink synchronized methods to synchronized blocks to guard ONLY operations that involve shared state Polled and timed lock attempts See Lock interface in Java 5 acquisition of locks may be interrupted 13
14 Outline Deadlocks Dining Philosophers Lock Ordering Reducing Lock Granularity Open calls Use of polling and timeouts Atomic acquisition of multiple locks Semaphores Lock Striping 14
15 Dining Philosophers Problem Each fork is a shared resource with actions get and put. FORK left phil[1]: PHIL right phil[0]: PHIL left FORK right phil[4]: PHIL When hungry, each PHIL must first get his right and left forks before he can start eating right left FORK phil[2]: PHIL right FORK left left FORK right phil[3]: PHIL 15
16 Dining Philosophers Problem class Fork { private boolean taken=false; final int identity; public Fork (int i) { identity = i; synchronized void put() { taken=false; notify(); synchronized void get() throws java.lang.interruptedexception { while (taken) wait(); taken=true; 16
17 Dining Philosophers Problem public class Philosopher extends Thread { final int identity; final Fork left; final Fork right; public Philosoper (int identity, Fork left, Fork right) { this.identity = identity; this.left = left; this.right = public void run() { // see next slide 17
18 Dining Philosophers Problem public void run() { try { while (true) { sleep(thinktime); right.get(); left.get(); sleep(eattime); // thinking // hungry // got right fork // got left fork // eating right.put(); left.put(); catch (java.lang.interruptedexception e){ 18
19 Dining Philosophers Problem Code to create the philosopher threads and fork monitors: for (int i =0; i<n; ++i) { fork[i] = new Fork(i); for (int i =0; i<n; ++i) { phil[i] = new Philosopher (i, fork [i],fork [(i+1)%n]); phil[i].start(); 19
20 Solving The Philosophers Problem Deadlock can be avoided by ensuring that a wait-for cycle cannot exist. but how? Introduce an asymmetryinto our definition of philosophers Use the identity of a philosopher to make even numbered philosophers get their left forks first Odd numbered philosophers get their right forks first 20
21 Solving The Philosophers Problem public void run() { try { while (true) { sleep(thinktime); // thinking // hungry if (identity%2 == 0) { left.get(); right.get(); else { right.get(); left.get(); // got forks sleep(eattime); // eating right.put(); left.put(); catch (java.lang.interruptedexception e){ No wait-for cycle is possible! Cycle is broken because of reversal of order of acquisition by odd Philosophers Philosophers respect a protocol for lock acquisition 21
22 SolvingThe Philosophers Problem There are other solutions to the problem A simpler variation is just to break the cycle that causes the potential deadlock in just one place All Philosophers acquire forks in left right order, except for one e.g. the last one In effect, this places on order on the forks i< j implies Fork[i] < Fork [j] With an acquisition protocol that lower ordered forks must be acquired first So the last Philosopher[N-1] must acquire her right Fork [0] before the left Fork [N-1] Any other Philosopher[i] acquires left Fork[i] before right Fork [i+1] 22
23 Outline Deadlocks Dining Philosophers Lock Ordering Reducing Lock Granularity Open calls Use of polling and timeouts Atomic acquisition of multiple locks Semaphores Lock Striping 23
24 Recall Lock-Ordering Deadlock public void transfermoney(account fromaccount, Account toaccount, DollarAmountamount) throws InsufficientFundsException{ synchronized (fromaccount){ synchronized (toaccount){ if (fromaccount.getbalance().compareto(amount) < 0) else { fromaccount.debit(amount); toaccount.credit(amount); throw new InsufficientFundsException(); transfermoney(myaccount, youraccount, 10); transfermoney(youraccount, myaccount, 20); 24
25 Ensuring Lock-Ordering The order of arguments cannot be controlled within the definition of the transfer method To avoid deadlock, we can impose a global ordering on locks In Java use object identity Or rather, it s hashcode: System.identityHashCode(Object o) BUT occasionally different objects will have the same hashcode So handle that case specially 25
26 Ensuring Lock-Ordering public void transfermoney(account fromacct, Account toacct, DollarAmount amount) throws InsufficientFundsException{ int fromhash = System.identityHashCode(fromAcct); inttohash= System.identityHashCode(toAcct); if (fromhash< tohash) { synchronized (fromacct){ synchronized (toacct){/* do transfer */ else { synchronized (toacct){ synchronized (fromacct){/* do transfer */ This orders lock acquisition according to the hash of the locks object identity. This imposes a global ordering on all locks (except when they have the same hash) 26
27 Ensuring Lock-Ordering private static final Object tielock = new Object(); public void transfermoney(account fromacct, Account toacct, DollarAmount amount) throws InsufficientFundsException{ int fromhash = System.identityHashCode(fromAcct); inttohash= System.identityHashCode(toAcct); if (fromhash< tohash) { synchronized (fromacct) { synchronized (toacct){/* do transfer */ else if (fromhash> tohash) { synchronized (toacct){ synchronized (fromacct) {/* do transfer */ else { synchronized (tielock){ synchronized (fromacct) { synchronized (toacct){/* do transfer */ Use a single extra lock to deal with tied hashcodes. This ensures that both account locks can only be acquired by a single thread. It will rarely be used, so should not be a concurrency bottle-neck. 27
28 Outline Deadlocks Dining Philosophers Lock Ordering Reducing Lock Granularity Open calls Use of polling and timeouts Atomic acquisition of multiple locks Semaphores Lock Striping 28
29 Lock-Ordering Between Objects class Taxi { private Point location, destination; private final Dispatcher dispatcher; public synchronized Point getlocation() { return location; Could this be deadlocked? public synchronized void setlocation(point location) { this.location= location; if (location.equals(destination)) dispatcher.notifyavailable(this); The method call to dispatcher is an example of using an alienmethod. Such calls may be prone to deadlock when made within synchronized blocks. 29
30 Lock-Ordering Between Objects class Taxi { private Point location, destination; private final Dispatcher dispatcher; public synchronized Point getlocation(){ return location; class Dispatcher { private final Set<Taxi> taxis; private final Set<Taxi> availabletaxis; public synchronized void notifyavailable(taxi taxi) { availabletaxis.add(taxi); public synchronized void setlocation(point location) { this.location= location; if (location.equals(destination)) dispatcher.notifyavailable(this); public synchronized Image getimage(){ Image image= new Image(); for (Taxi t : taxis) image.drawmarker(t.getlocation()); return image; In Taxi, setlocation acquires its implicit (Taxi instance) lock, then dispatcher lock. In Dispatcher, getimage acquires its own lock, then that of its taxis. Potential DEADLOCK!, even though there is no direct cycle of calls. The problem is that different threads can request locks in different orders. 30
31 Open Calls Calling a method with no locks held is called an open call Classes that rely on open calls are better behaved and easier to use correctly than classes that make calls with locks held The Taxi-Dispatcher problem can be fixed by making the Dispatcher calls to Taxi open In effect we reduce the granularity or scope of the lock to avoid Taking care to maintain consistent behaviour 31
32 AvoidingDeadlock with Open Calls class Taxi { private Point location, destination; private final Dispatcher dispatcher;... public synchronizedvoid setlocation(point location) { this.location= location; if (location.equals(destination)) dispatcher.notifyavailable(this); BAD! class Taxi { private Point location, destination; private final Dispatcher dispatcher; public void setlocation(point location){ booleanreacheddestination; synchronized (this){ this.location= location; reacheddestination= location.equals(destination); if (reacheddestination) dispatcher.notifyavailable(this); GOOD! Call to dispatcher is open 32
33 Avoiding Deadlock with Open Calls class Dispatcher { private final Set<Taxi> taxis; private final Set<Taxi> availabletaxis; public synchronizedimage getimage(){ Image image= new Image(); for (Taxi t : taxis) image.drawmarker(t.getlocation()); return image; Note use of snapshot copy to allow scope of implicit lock to be limited BAD! class Dispatcher { private final Set<Taxi> taxis; private final Set<Taxi> availabletaxis; public Image getimage(){ Set<Taxi> copy; synchronized (this){ copy = new HashSet<Taxi>(taxis); Image image= new Image(); for (Taxi t : copy) image.drawmarker(t.getlocation()); return image; GOOD! Call to taxis t are open 33
34 Outline Deadlocks Dining Philosophers Lock Ordering Reducing Lock Granularity Open calls Use of polling and timeouts Atomic acquisition of multiple locks Semaphores Lock Striping 34
35 One-HitAcquisition of Multiple Locks Lock ordering is one approach to avoiding deadlock with code using multiple locks Another is the use of open calls Reducing scope / granularity of locks Another approach is to acquire multiple locks in an atomic action Attempt may succeed or fail If it fails, then any acquired locks must be released May then try again, possibly after a delay Can use polling or timeout to acquire locks 35
36 The Java locks package The java.util.concurrent.locks package since Java 5 Provide a framework for locking and waiting for conditions distinct from built-in synchronization and monitors. Interfaces: Lock, ReadWriteLock, Condition Classes: ReentrantLock, ReentrantReadWriteLock, ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock, LockSupport, AbstractQueuedSynchronizer 36
37 Intrinsic Locks vslock Objects Intrinsic locks it is not possible to interrupt a thread waiting to acquire a lock locks are acquired and released automatically must be acquired and released in the same block of code Lock objects offer a choice of unconditional, polled, timed, and interruptible lock acquisition all lock and unlock operations are explicit make non-block structured locking disciplines impossible 37
38 The Lock Interface Define abstract locking operations all lock and unlock operations are explicit All Lock implementations mustenforce the same memory synchronization semantics May use different locking acquisition unconditional, polled, timed, and interruptible public interface Lock { void lock(); void unlock(); booleantrylock();... 38
39 The ReentrantLockClass An implementation of the Lock interface A mutual exclusion lock similar to built-in locks Lock lock = new ReentrantLock(); lock.lock(); try { // update object state, and restore invariants if necessary finally { lock.unlock(); Always immediately follow lock() with a try/finally 39
40 The trylock() Method Used for polling a lock Always return immediately return false if lock is not available Lock lock= new ReentrantLock(); if (lock.trylock()) { try { // manipulate protected state finally { lock.unlock(); else { // perform alternative actions 40
41 Avoiding Deadlock with trylock() public class Friend { public synchronizedvoid bow(friend bower) { bower.bowback(this); public synchronizedvoid bowback(friend bower) { What can go wrong? Friend peter = new Friend(); Friend george = new Friend(); new Thread(new Runnable() { public void run() { peter.bow(george); ).start(); new Thread(new Runnable() { public void run() { george.bow(peter); ).start(); 41
42 Avoiding Deadlock with trylock() public class Friend { private final Lock lock= new ReentrantLock(); public void bow(friend bower) { if (impendingbow(bower)) { try { bower.bowback(this); finally { lock.unlock(); bower.lock.unlock(); Other code is not changed public booleanimpendingbow(friend bower) { Boolean mylock = false; Boolean yourlock = false; try { mylock = lock.trylock(); yourlock = bower.lock.trylock(); finally { if (!(mylock&& yourlock)) { if (mylock) lock.unlock(); if (yourlock) bower.lock.unlock(); return mylock&& yourlock; 42
43 Avoiding Deadlock with trylock() public class Friend { private final Lock lock= new ReentrantLock(); public void bow(friend bower) { if (impendingbow(bower)) { try { bower.bowback(this); finally { lock.unlock(); bower.lock.unlock(); Other code is not changed public booleanimpendingbow(friend bower) { Boolean mylock = false; Boolean yourlock = false; try { mylock = lock.trylock(); yourlock = bower.lock.trylock(); finally { if (!(mylock&& yourlock)) { if (mylock) lock.unlock(); if (yourlock) bower.lock.unlock(); return mylock&& yourlock; 43
44 Outline Deadlocks Dining Philosophers Lock Ordering Reducing Lock Granularity Open calls Use of polling and timeouts Atomic acquisition of multiple locks Semaphores Lock Striping 44
45 Semaphores The classic method for restricting access to shared resources by Edsger Dijkstra to prevent race conditions in the dining philosophers problem they do NOT prevent deadlocks A counting semaphore controls the number of activities that can access a certain resource A binary semaphore is a locked/unlocked flag of a single resource. i.e. mutual exclusion 45
46 Semaphores in Java 5 java.util.concurrent.semaphore Java semaphores manage a set of virtual permits Activities can acquire permits if no permit is available, they block until one is (or interrupted) Activities release permits when they are done with them 46
47 Semaphores in Java 5 The initial number of permits is given to the constructor A binary semaphore has a sole permit similar to Java locks, but does not support reentrant locking The initial number of permits may be zero or negative in such case, releases must occur before any acquires will be granted Correct usage of a semaphore is established by programming convention in the application 47
48 A Semaphore Example public class BoundedHashSet{ private final Set set; private final Semaphore sema; public BoundedHashSet(intbound){ this.set= Collections.synchronizedSet( new HashSet()); sema= new Semaphore(bound); public booleanremove(object o) { booleanwasremoved= set.remove(o); if (wasremoved) sema.release(); return wasremoved; public booleanadd(object o) throws InterruptedException{ sema.acquire(); booleanwasadded= false; try { wasadded= set.add(o); return wasadded; finally { if (!wasadded) sema.release(); 48
49 A Semaphore Example public class BoundedHashSet{ private final Set set; private final Semaphore sema; public BoundedHashSet(intbound){ this.set= Collections.synchronizedSet( new HashSet()); sema= new Semaphore(bound); public booleanremove(object o) { booleanwasremoved= set.remove(o); if (wasremoved) sema.release(); return wasremoved; public booleanadd(object o) throws InterruptedException{ sema.acquire(); booleanwasadded= false; try { wasadded= set.add(o); return wasadded; finally { if (!wasadded) sema.release(); 49
50 Implementing Resource Pools Semaphores are useful for implementing resource pools e.g. database connection pools Initialise a Semaphore to the pool size Acquire a permit before trying to fetch a resource from the pool acquire blocks until the pool becomes nonempty Release the permit after putting a resource back in the pool 50
51 Outline Deadlocks Dining Philosophers Lock Ordering Reducing Lock Granularity Open calls Use of polling and timeouts Atomic acquisition of multiple locks Semaphores Lock Striping 51
52 Lock Striping Finer-grained locks used especially for arraybased data structures Each part of the (array) data is protected by a separate lock Different parts may be accessed concurrently This is essentially a form of (internal) lock splitting ConcurrentHashMap provides a good example Avoids global data e.g. size is estimated by summing over each separate (protected) part 52
53 Lock Striping Example public class StripedMap{ // Synchronization policy: buckets[n] // guarded by locks[n%n_locks] private static final int N_LOCKS = 16; private final Node[] buckets; private final Object[] locks; public StripedMap(int numbuckets) { buckets = new Node[numBuckets]; locks = new Object[N_LOCKS]; for (inti= 0; i< N_LOCKS; i++) locks[i] = new Object(); private static class Node { Node next; Object key; Object value; private final int hash(object key) { return Math.abs(key.hashCode() % buckets.length); 2010 John Potter and Yi Lu CSE UNSW Sydney 53
54 Lock Striping Example public Object get(object key) { int i= hash(key); synchronized (locks[i% N_LOCKS]) { for (Node m = buckets[hash]; m!= null; m = m.next) if (m.key.equals(key)) return m.value; return null; public void clear() { for (inti= 0; i< buckets.length; i++) { synchronized (locks[i% N_LOCKS]){ buckets[i] = null; 2010 John Potter and Yi Lu CSE UNSW Sydney 54
Concurrency in Object Oriented Programs 3. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter
Concurrency in Object Oriented Programs 3 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Explicit Locks in Java Techniques for Concurrent Reading State Dependent
More informationConcurrency: Deadlock 1. Magee/Kramer 2 nd Edition
Concurrency: Deadlock 1 Concurrency: Deadlock 2 Chapter 6 Deadlock Concurrency: Deadlock 3 Deadlock Concepts: system deadlock: no further progress four necessary & sufficient conditions Models: deadlock
More informationChapter 6. Deadlock Concurrency: Deadlock. Magee/Kramer 2 nd Edition
Chapter 6 Deadlock 1 Deadlock Concepts: Models: system deadlock: no further progress four necessary & sufficient conditions deadlock - no eligible actions Practice: blocked threads Aim: deadlock avoidance
More informationDeadlock. Concepts: Models: Practice: Aim: deadlock avoidance - to design systems where deadlock cannot occur. Chapter 6. Deadlock
Chapter 6 Deadlock Deadlock Concepts: Models: Practice: system deadlock: no further progress four necessary & sufficient conditions deadlock - no eligible actions blocked threads Aim: deadlock avoidance
More informationCOMP 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 informationDeadlock. INF2140 Parallel Programming: Lecture 6. March 07, INF2140 Parallel Programming: Lecture 6 Deadlock
March 07, 2012 Concepts System deadlock: no further progress Four necessary & sufficient conditions Models - no eligible actions Practice Blocked threads Aim: deadlock avoidance - to design systems where
More informationJFokus 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 informationChapter 6. Deadlock. DM519 Concurrent Programming
Chapter 6 Deadlock 1 But First: Repetition Monitors and Condition Synchronisation 2 Monitors & Condition Synchronisation Concepts: monitors: Models: encapsulated data + access procedures + mutual exclusion
More information3C03 Concurrency: Starvation and Deadlocks
3C03 Concurrency: Starvation and Deadlocks Wolfgang Emmerich 1 Goals Reader/Writer problem Starvation Dining Philosophers Problem Deadlocks Liveness Analysis using LTS 2 1 Reader / Writer Problem Monitors
More informationJava Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency
Java Threads Vs Processes CS6868 - Concurrent Programming Java Concurrency V. Krishna Nandivada Typically each instance of JVM creates a single process. Each process creates one or more threads. Main thread
More informationCMSC 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 informationContribution: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 informationG52CON: 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 informationCMSC 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 informationThreads 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 informationNortheastern University - Seattle CS5510 Professor Ian Gorton
Northeastern University - Seattle CS5510 Professor Ian Gorton Northeastern University 1 Week 10 CONCURRENCY II Northeastern University 2 http://jcip.net/ 3 Overview Loops/recursion and threads Readers
More informationSynchronized 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 informationDUBLIN 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 informationSFDV3006 Concurrent Programming
SFDV3006 Concurrent Programming Lecture 6 Deadlocks, livelocks, Starvation Introduction Last week we covered semaphore and how to use them for both synchronization and condition synchronization This week
More informationMore 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 informationThe 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 informationConcurrency 6 - Deadlock
Concurrency 6 - Deadlock Monitors & Condition Synchronization - Repetition!!"! "#$! %!#$ &' (&') #&' #&' # wait(), notify(), and notifyall() - Repetition public final void wait() throws InterruptedException;
More informationCOMP 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 informationSynchronization. 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 informationProcess Management And Synchronization
Process Management And Synchronization In a single processor multiprogramming system the processor switches between the various jobs until to finish the execution of all jobs. These jobs will share the
More informationDeadlock Victim && && && && by Dr Heinz Kabutz The Java Specialists Newsletter
1 Deadlock Victim by Dr Heinz Kabutz The Java Specialists Newsletter heinz@javaspecialists.eu twitter: @heinzkabutz && && && && Olivier Croisier The Coder's Breakfast olivier.croisier@zenika.com twitter:
More informationRecap. 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 informationG Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University
G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12
More informationOperating 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 informationCS 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 informationTHREADS & 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 informationConcurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter
Concurrency in Object Oriented Programs 1 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Concurrency: the Future of Computing Java Concurrency Thread Safety
More informationCOMP 322: Fundamentals of Parallel Programming
COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 30: Advanced locking in Java Vivek Sarkar Department of Computer Science Rice University
More informationProcess Synchronization
CSC 4103 - Operating Systems Spring 2007 Lecture - VI Process Synchronization Tevfik Koşar Louisiana State University February 6 th, 2007 1 Roadmap Process Synchronization The Critical-Section Problem
More informationLiveness properties. Deadlock
Liveness properties From a theoretical viewpoint we must ensure that we eventually make progress i.e. we want to avoid : blocked threads/processes waiting for each other Livelock: processes/threads execute
More informationThe deadlock problem
Deadlocks Arvind Krishnamurthy Spring 2004 The deadlock problem A set of blocked processes each holding a resource and waiting to acquire a resource held by another process. Example locks A and B P 0 P
More informationCMSC 330: Organization of Programming Languages. Concurrency & Multiprocessing
CMSC 330: Organization of Programming Languages Concurrency & Multiprocessing Multiprocessing Multiprocessing: The use of multiple parallel computations We have entered an era of multiple cores... Hyperthreading
More informationCSE332: Data Abstractions Lecture 25: Deadlocks and Additional Concurrency Issues. Tyler Robison Summer 2010
CSE332: Data Abstractions Lecture 25: Deadlocks and Additional Concurrency Issues Tyler Robison Summer 2010 1 Where we are We ve covered basic concurrency, then some odds and ends: Readers/writer locks
More informationCSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014
CSE 332: Locks and Deadlocks Richard Anderson, Steve Seitz Winter 2014 1 Recall Bank Account Problem class BankAccount { private int balance = 0; synchronized int getbalance() { return balance; } synchronized
More informationMultithreaded 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 informationSummary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data
Lecture 4 Monitors Summary Semaphores Good news Simple, efficient, expressive Passing the Baton any await statement Bad news Low level, unstructured omit a V: deadlock omit a P: failure of mutex Synchronisation
More informationChair 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 informationClassical Synchronization Problems. Copyright : University of Illinois CS 241 Staff 1
Classical Synchronization Problems 1 1 This lecture Goals: Topics Introduce classical synchronization problems Producer-Consumer Problem Reader-Writer Problem Dining Philosophers Problem Sleeping Barber
More informationTHE QUEEN S UNIVERSITY OF BELFAST
THE QUEEN S UNIVERSITY OF BELFAST FSP Quick Reference Guide is attached to the end of the examination paper. 110CSC321 Level 3 EXAMINATION FOR THE DEGREE(S) OF MEng, BEng, BSc Concurrent Programming January
More informationLecture 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 informationCMSC 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 informationThreads. Concurrency. What it is. Lecture Notes Week 2. Figure 1: Multi-Threading. Figure 2: Multi-Threading
Threads Figure 1: Multi-Threading Figure 2: Multi-Threading Concurrency What it is 1. Two or more threads of control access a shared resource. Scheduler operation must be taken into account fetch-decode-execute-check
More informationTHREADS & 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 informationReintroduction 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 informationModule 6: Process Synchronization. Operating System Concepts with Java 8 th Edition
Module 6: Process Synchronization 6.1 Silberschatz, Galvin and Gagne 2009 Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores
More informationEI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)
EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) Dept. of Computer Science & Engineering Chentao Wu wuct@cs.sjtu.edu.cn Download lectures ftp://public.sjtu.edu.cn User:
More informationSynchronization. Silvina Hanono Wachman Computer Science & Artificial Intelligence Lab M.I.T.
Synchronization Silvina Hanono Wachman Computer Science & Artificial Intelligence Lab M.I.T. L24-1 Reminders All labs must be completed by this Friday, Dec. 7 th to pass the course Any work you intend
More informationProcessor speed. Concurrency Structure and Interpretation of Computer Programs. Multiple processors. Processor speed. Mike Phillips <mpp>
Processor speed 6.037 - Structure and Interpretation of Computer Programs Mike Phillips Massachusetts Institute of Technology http://en.wikipedia.org/wiki/file:transistor_count_and_moore%27s_law_-
More informationThreads 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 information5. Liveness and Guarded Methods
5. Liveness and Guarded Methods Prof. O. Nierstrasz Selected material Magee and Kramer Roadmap > Liveness Progress Properties > Deadlock The Dining Philosophers problem Detecting and avoiding deadlock
More informationConcurrent Programming
Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as
More informationConcurrency: Principles of Deadlock. Processes and resources. Concurrency and deadlocks. Operating Systems Fall Processes need resources to run
Concurrency: Principles of Deadlock Operating Systems Fall 2002 Processes and resources Processes need resources to run CPU, memory, disk, etc process waiting for a resource cannot complete its execution
More informationre-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M)
re-exam Concurrent Programming tda383/dit390 Date: 2016-08-22 Time: 14:00 18:00 Place: Maskinhuset (M) Responsible Michał Pałka 031 772 10 79 Result Available no later than 2016-09-12 Aids Max 2 books
More informationIV. Process Synchronisation
IV. Process Synchronisation Operating Systems Stefan Klinger Database & Information Systems Group University of Konstanz Summer Term 2009 Background Multiprogramming Multiple processes are executed asynchronously.
More informationJava 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 informationOperating Systems Antonio Vivace revision 4 Licensed under GPLv3
Operating Systems Antonio Vivace - 2016 revision 4 Licensed under GPLv3 Process Synchronization Background A cooperating process can share directly a logical address space (code, data) or share data through
More informationSSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)
SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics
More informationCMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions
CMSC 433 Programming Language Technologies and Paradigms Fall 2011 Locks & Conditions Intrinsic Lock Example public class RWDictionaryIntrinsicLock { Map m = new TreeMap();
More informationSemaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University
Semaphores Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Synchronization
More informationJava Platform Concurrency Gotchas
Java Platform Concurrency Gotchas Alex Miller Terracotta Questions to answer > What are common concurrency problems? > Why are they problems? > How do I detect these problems? > How do I correct these
More informationSynchronization problems with semaphores
Synchronization problems with semaphores Lecture 4 of TDA384/DIT391 (Principles of Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2017/2018 Today
More informationChapter 6: Synchronization. Operating System Concepts 8 th Edition,
Chapter 6: Synchronization, Silberschatz, Galvin and Gagne 2009 Outline Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization
More informationCSL373: 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 informationMore thread safety and Concurrent collections. Nasser Giacaman CompSci 230: Software Design and Construction
More thread safety and Concurrent collections Nasser Giacaman CompSci 230: Software Design and Construction 1 Today's lecture More on Java's mutual exclusion tools Intrinsic locks Developing our own thread-safe
More informationMore on Synchronization and Deadlock
Examples of OS Kernel Synchronization More on Synchronization and Deadlock Two processes making system calls to read/write on the same file, leading to possible race condition on the file system data structures
More informationThreads 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 informationInterprocess Communication By: Kaushik Vaghani
Interprocess Communication By: Kaushik Vaghani Background Race Condition: A situation where several processes access and manipulate the same data concurrently and the outcome of execution depends on the
More informationConcurrency & 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 informationDeadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018
Deadlock and Monitors CS439: Principles of Computer Systems September 24, 2018 Bringing It All Together Processes Abstraction for protection Define address space Threads Share (and communicate) through
More informationOPERATING SYSTEMS. Deadlocks
OPERATING SYSTEMS CS3502 Spring 2018 Deadlocks Chapter 7 Resource Allocation and Deallocation When a process needs resources, it will normally follow the sequence: 1. Request a number of instances of one
More informationConcurrency, 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 informationCS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers
CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some
More informationRoadmap. Readers-Writers Problem. Readers-Writers Problem. Readers-Writers Problem (Cont.) Dining Philosophers Problem.
CSE 421/521 - Operating Systems Fall 2011 Lecture - X Process Synchronization & Deadlocks Roadmap Classic Problems of Synchronization Readers and Writers Problem Dining-Philosophers Problem Sleeping Barber
More informationOperating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst
Operating Systems CMPSCI 377 Spring 2017 Mark Corner University of Massachusetts Amherst Clicker Question #1 public static void main(string[] args) { (new Thread(new t1())).start(); (new Thread(new t2())).start();}
More informationVerification of Java programs using networks of finite automata with discrete data.
Catholic University in Ružomberok Scientific Issues, Mathematica II, Ružomberok 2009 Verification of Java programs using networks of finite automata with discrete data. Bożena Woźna, Andrzej Zbrzezny Institute
More informationLecture 29: Java s synchronized statement
COMP 322: Fundamentals of Parallel Programming Lecture 29: Java s synchronized statement Vivek Sarkar Department of Computer Science, Rice University vsarkar@rice.edu https://wiki.rice.edu/confluence/display/parprog/comp322
More informationThreads, 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 informationTHREADS 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 informationCMSC 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 informationCHAPTER 6: PROCESS SYNCHRONIZATION
CHAPTER 6: PROCESS SYNCHRONIZATION The slides do not contain all the information and cannot be treated as a study material for Operating System. Please refer the text book for exams. TOPICS Background
More informationLesson 6: Process Synchronization
Lesson 6: Process Synchronization Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks Semaphores Classic Problems of Synchronization
More informationCS3502 OPERATING SYSTEMS
CS3502 OPERATING SYSTEMS Spring 2018 Synchronization Chapter 6 Synchronization The coordination of the activities of the processes Processes interfere with each other Processes compete for resources Processes
More informationThe University of Texas at Arlington
The University of Texas at Arlington Lecture 6: Threading and Parallel Programming Constraints CSE 5343/4342 Embedded Systems II Based heavily on slides by Dr. Roger Walker More Task Decomposition: Dependence
More informationCS 10: Problem solving via Object Oriented Programming Winter 2017
CS 10: Problem solving via Object Oriented Programming Winter 2017 Tim Pierson 260 (255) Sudikoff SynchronizaGon Agenda 1. Threads and interleaving execugon 2. Producer/consumer 3. Deadlock, starvagon
More informationProcess Synchronization
Process Synchronization Chapter 6 2015 Prof. Amr El-Kadi Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly
More informationMultiThreading 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 informationCSE 4/521 Introduction to Operating Systems
CSE 4/521 Introduction to Operating Systems Lecture 7 Process Synchronization II (Classic Problems of Synchronization, Synchronization Examples) Summer 2018 Overview Objective: 1. To examine several classical
More informationChapter 6: Process Synchronization. Module 6: Process Synchronization
Chapter 6: Process Synchronization Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization
More informationCS 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 informationAdvanced 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 informationDeadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018
Deadlock and Monitors CS439: Principles of Computer Systems February 7, 2018 Last Time Terminology Safety and liveness Atomic Instructions, Synchronization, Mutual Exclusion, Critical Sections Synchronization
More informationDeadlocks. Copyright : University of Illinois CS 241 Staff 1
Deadlocks 1 Deadlock Which way should I go? 2 Deadlock I Oh can no! almost I m get stuck! across GRIDLOCK! 3 Deadlock Definition Deadlocked process Waiting for an event that will never occur Typically,
More informationResource Allocation - Dining Philosophers. Dining Philosophers - Properties. OK? EATING[(i%N)+1]) Impossibility Result for Symmetric Algorithm
Resource Allocation - Dining Philosophers Dining Philosophers - Properties Five philosophers sit around a circular table. Each philosopher spends his life alternately thinking and eating. In the centre
More informationDealing 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 informationThreads 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