Concurrency in Object Oriented Programs 3. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

Size: px
Start display at page:

Download "Concurrency in Object Oriented Programs 3. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter"

Transcription

1 Concurrency in Object Oriented Programs 3 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

2 Outline Explicit Locks in Java Techniques for Concurrent Reading State Dependent Access Deadlocks and Lock Ordering 2

3 Implicit Locks in Java recall: every object has an intrinsic monitor only one thread can enter a monitor at a time provides single threaded access to critical sections of code provides mutual exclusion synchronized statements enforce structured use of the monitor implicit, complementary monitor enter and monitor exit operations locks are automatically released at end of code block/ method, even if exceptions are thrown object monitors are reentrant one thread may enter the implicit monitor more than once object monitors are released while an object is waiting see State Dependent Access in these slides 3

4 Explicit Locks in Java explicit mutex locks c.f. instrinsic monitor extra lock functionality nonblocking acquire client must handle failure to acquire interruptible acquire a blocked attempt may be interrupted acquire with timeout more flexible use without lexical scope e.g. controlling concurrent top-down access to branches of a tree per-node locks must acquire child lock before release of parent lock so-called hand-over-hand or chain locking ensures no overtaking down any branch of a tree but note that tree root is a potential point of contention for concurrent access may support Condition objects see later 4

5 In java.util.concurrent.locks public interface Lock { void lock (); void unlock (); boolean trylock (); boolean trylock (long time, TimeUnit unit) throws InterruptedException; void lockinterruptibly () throws InterruptedException; Condition newcondition (); public class ReentrantLock implements Lock {... 5

6 Use of Explicit Locks in Java programmer is responsible for correct management of locks standard code idiom lock acquire try protected access finally lock release guarantees release of lock, even with exceptions Java code outline: Lock l =...; // e.g. new ReentrantLock () l.lock(); try { // access the resource protected by this lock finally { l.unlock(); 6

7 Mutual Exclusion vs Immutability mutual exclusion in Java objects with methods protected by mutual exclusion are updatable but are NOT concurrently accessible immutable objects no locking required objects, after being "safely" constructed are concurrently accessible but are NOT updatable both approaches can prevent race conditions what about concurrent access to read-mostly objects? updates are infrequent write/read ratio is low but > 0 cannot use immutable objects mutual exclusion is too strong we want concurrent reads 7

8 Outline Explicit Locks in Java Techniques for Concurrent Reading State Dependent Access Deadlocks and Lock Ordering 8

9 Concurrent Reading two approaches may yield better performance when reads outnumber writes read-write locks holding write permission blocks other reads and writes holding read permission blocks writes, not reads copy-on-write only mutable data is a (volatile) reference to an immutable object reads require no synchronization all read methods must only access the reference once to avoid data races with any write methods writes create a new immutable object, possibly reading the reference and reassigning it writes do require synchronization active reads may still be accessing the old data they continue to see the old state of the object see examples in j.u.c package CopyOnWriteArrayList CopyOnWriteArraySet 9

10 Read-Write Locks allow a resource to be accessed by multiple readers or a single writer at a time, but not both allow a greater level of concurrency in accessing shared data than a mutex especially when locks may be held for a long time and most operations are read only in java.util.concurrent.locks: public interface ReadWriteLock { Lock readlock(); Lock writelock(); public class ReentrantReadWriteLock implements ReadWriteLock {... 10

11 Read-Write Lock Example public class Table { private final Map<String, Data> map; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock r = lock.readlock(); private final Lock w = lock.writelock(); public Data get(string key) { r.lock(); try { return map.get(key finally { r.unlock(); public void put(string key, Data value) { w.lock(); try { map.put(key, value); finally { w.unlock(); Mul3ple threads may run get() Only one thread may run put() 11

12 Read-Write vs Mutex RW offers increased concurrency by allowing concurrent reads but if all reads are short-lived, and there are frequent writes overhead of RW lock may not be justifiable code techniques to allow simple RW/mutex swaps with minimal code change: choose a RWLock factory which makes either a RW lock, e.g. a standard ReentrantReadWriteLock or a mutex, via a RWLock decorator for a standard (mutex) ReentrantLock where the read and write locks are the same use decorators to construct synchronized code synchronized vs explicit mutex vs read-write choice of decorator is when synchronized object is constructed 12

13 Read-Write Lock Policies when both readers and writers are waiting, should a read or a write be granted? should access be granted in-order, or fairly? when a reader is active and a writer is waiting, should a new read be granted (overtaking the waiting writer) reader preference risks writer starvation writer preference may reduce concurrency reentrancy for RW locks: what does it mean? can a thread with a write lock reacquire it? Can it acquire the read lock? can a thread with a read lock reacquire it? can locks be downgraded (from write to read) or upgraded (from read to write), with no intervention by other threads? 13

14 Read-Write Locks and Starvation reading threads may acquire a lock if the lock is held for reading by another thread when will a writer be able to grab the lock? maybe never it has to wait for ALL readers to finish, but before then new readers can always grab the lock and run a solution: writer s preference implemented in Java's j.u.c.l.reentrantreadwritelock do not grant the read lock to a new thread if there is a writer waiting for the lock an optional fairness flag gives the longest-waiting thread priority for locks j.u.c.l. is abbrevia3on for package name: java.u3l.concurrent.locks 14

15 Outline Explicit Locks in Java Techniques for Concurrent Reading State Dependent Access Deadlocks and Lock Ordering 15

16 State Dependence in sequential programming a method precondition specifies the state an object must be in for a call to be correct the client code is responsible for ensuring the target object is in a suitable state or otherwise not calling the method in concurrent programming client code cannot control the state of the target object except by acquiring a mutex, which sacrifices concurrency otherwise, independent threads may modify the object instead clients need to wait for the required condition to occur 16

17 Examples of State Dependent Operations operations on collections, streams, databases remove an element from an empty queue operations on objects maintaining constrained values withdraw money from an empty bank account operations requiring resources print a file operations requiring particular message orderings read an unopened file operations on external controllers shift to reverse gear in a moving car 17

18 Bounded Buffer public class BoundedBuffer { final Object[] buf; final int capacity; int head, tail, count; public BoundedBuffer(int cap){ capacity = cap; buf = new Object[capacity]; head = tail = count = 0; public int count() { return count; public int capacity(){ return capacity; public void put(object item) throws Failure { if (count == capacity) throw new Failure(); else { // store item at tail count++; buf[tail] = item; tail = (tail+1) % capacity; public Object remove() throws Failure { if (count == 0) throw new Failure(); else { // remove item at head Object item = buf[head]; count_--; head = (head+1) % capacity; return item; 18

19 Safety in Bounded Buffer typical usage of the bounded buffer in a sequential environment: caller checks precondition before making call via check-and-act: if (buffer.count()<buffer.capacity()) { buffer.put(item); if (buffer.count()>0) { item = buffer.get(); check-and-act can often fail in concurrent environments condition may be invalidated by a concurrent thread so an action should not go ahead even though its check succeeded condition may be made valid by a concurrent thread so an action could have gone ahead even when its check failed concurrent puts or removes may interfere with each other because they update buffer data simple locks (mutex or RW) can provide safety but clients will still need to synchronize the check-and-act code themselves 19

20 Interfaces and Policies public interface BoundedBuffer { int capacity(); // Inv: capacity() > 0 int count(); // Inv: 0 <= count() <= capacity() // Init: count() == 0 void put(object x); // Pre: count() < capacity() Object remove(); // Pre: count() > 0 interfaces alone cannot convey policy but can suggest policy for example, remove() throws an exception public Object remove() throws Failure { different methods can support different policies can also use annotations indicate whether action is state dependent with design by contract support: make preconditions explicit 20

21 State Dependence operations may succeed only if object is in particular logical state choose the policy (precondition) for the operation interfaces or protocols reflect policy operations check the state they depend on to implement policy 21

22 Policies for State Dependent Actions Blind action: Proceed regardless; no guarantee of outcome Inaction: Ignore request Balking: Report failure Guarding: Wait until in right state Trying: Proceed anyway, check if action succeeded; if not fail Retrying: Keep trying until success Timing out: Wait or retry for a while; then fail Planning: Try to achieve the right state 22

23 Balking check state upon method entry fail immediately if not in the right state responsibility for handling failure thrown to client usable in both concurrent and sequential contexts 23

24 Bounded Buffer with Balking public class BoundedBuffer { final Object[] buf; final int capacity; int head, tail, count; public BoundedBuffer(int cap){ capacity = cap; buf = new Object[capacity]; head = tail = count = 0; public int count() { return count; public int capacity(){ return capacity; synchronized public void put(object item) throws Failure { if (count == capacity) throw new Failure(); else { // store item at tail count++; buf[tail] = item; tail = (tail+1) % capacity; synchronized public Object remove() throws Failure { if (count == 0) throw new Failure(); else { // remove item at head Object item = buf[head]; count_--; head = (head+1) % capacity; return item; 24

25 Propagating Precondition Failure BoundBuffer buffer; while (true) { try { to Callers item = buffer.get(); // throw Failure if buffer is empty break; // if ok, break the loop catch (Failure e) { Thread.sleep(SLEEP_GRANULARITY); // pause before retry // use item Callers have to deal with precondition failures themselves 25

26 Guarding callers do not have to deal with precondition failure the retry mechanism is encapsulated within the methods the calling thread waits until the precondition is true requires another thread to make an update that enables the precondition the waiting thread needs to be notified of the update to allow the precondition to be checked again client code does not implement the retry logic on each call but clients need to be aware that calls may wait 26

27 Guarding locks cause blocking locks cannot be acquired if held by other threads guards cause waiting appropriate for state dependent actions wait until some action precondition is true need other threads to make updates in a sequential context, guarding is useless because no other thread can change the state once waiting, will wait for ever so a client must ensure precondition is true before making a call 27

28 Guarding Mechanisms busy waiting thread continually spins waiting for condition while (!condition) ; // spin consumes CPU time if the condition does not change requires multiple-cpu s or timeslicing it is inappropriate for Java application programming suspension thread stops execution until notified that the condition may be true supported in Java via wait-sets and locks wait(), notify(), notifyall() 28

29 Guarding via wait/notify Java supports guarding with suspension waiting for a condition: synchronized(foo) { while (!condition) { try { foo.wait(); catch ( InterruptedException ex) { condition is true // proceed changing a condition: synchronized(foo) { condition = true; foo.notifyall(); // or foo.notify(); 29

30 Wait-sets and Notification every Java object has a wait-set can only be manipulated while the object lock is held (via synchronized statements) otherwise, IllegalMonitorStateException is thrown threads enter the wait-set by invoking wait() wait() releases the current object lock and the thread is placed in the objects wait-set (and waits) includes releasing a lock held multiple times (via re-entries) no other locks held by the thread are released (caution!) lock is reacquired before wait() returns lock count is restored optional timed-wait: wait(long millisecond) 30

31 Wait-sets and Notification wait(long) causes current thread to wait till another thread invokes the notify()/notifyall() method for this object or a specified amount of time has elapsed threads are released from the wait-set when other threads invoke: notify() releases a single thread from the wait-set which thread is not defined, so avoid using this! only OK to use when you know at most thread can be waiting notifyall() releases all threads 31

32 Bounded Buffer with Guarding synchronized public void put(object item) { while (count == capacity) { try { wait(); catch (InterruptedException e){ count++; buf[tail] = item; // store item at tail tail = (tail+1) % capacity; notifyall(); // no longer empty synchronized public Object get() { while (count == 0) { try { wait(); catch (InterruptedException e){ // remove item at head Object item = buf[head]; count--; head = (head+1) % capacity; notifyall(); // no longer full return item; 32

33 Condition Variables in Java there is only one wait-set per object with notifyall() there is no way to know which threads should be released from the wait-set so they are all released condition variables provide separate wait-sets for different conditions in j.c.u.l a Condition belongs to an explicit Lock a Condition factors out the wait-set methods: called await, signal, signalall like wait, notify, notifyall multiple Conditions provide ability to associate multiple wait-sets with an object explicit conditions allow for specific notifications using signal instead of signalall only one thread is released per signal ensure that the thread must be waiting on that condition and nothing else if a thread may wait on some other condition then a woken thread may await again the notification has been lost in general: avoid specific notification if there are multiple conditions that may cause a thread to wait use signalall to avoid lost notifications in such cases 33

34 Bounded Buffer with Conditions public class BoundedBuffer { final Lock lock = new ReentrantLock(); final Condition notfull = lock.newcondition(); final Condition notempty = lock.newcondition(); final Object[] buf; final int capacity; int head, tail, count; public BoundedBuffer(int cap){ capacity = cap; buf = new Object[capacity]; head = tail = count = 0; public int count() { return count; public int capacity(){ return capacity; public void put(object item) throws InterruptedException { lock.lock(); try { while (count == capacity) notfull.await(); count++; buf[tail] = item; tail = (tail+1) % capacity; notempty.signal(); finally { lock.unlock(); public Object get() throws InterruptedException { lock.lock(); try { while (count == 0) notempty.await(); Object item = buf[head]; count--; head = (head+1) % capacity; notfull.signal(); return item; finally { lock.unlock(); 34

35 Outline Explicit Locks in Java Techniques for Concurrent Reading State Dependent Access Deadlocks and Lock Ordering 35

36 Deadlocks Liveness is a concurrent application's ability to execute in a timely manner tension between safety and liveness safety is achieved via controls that block execution this inhibits liveness Deadlock occurs in a program when some threads are permanently blocked occurs when 2 or more threads are blocked on a shared resource held by another Java applications do not recover from deadlock so we must design to avoid the possibility of deadlock 36

37 Four Conditions for Deadlock Serially reusable resources a resource is either assigned to one thread or it is available No pre-emption 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 37

38 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 pre-emption 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 addresses / object hashcodes these last 2 points will be considered in this lecture 38 manage resources hierarchically

39 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(); 39

40 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 40

41 Deadlock Prone? public void transfermoney(account fromaccount, Account toaccount, DollarAmount amount) throws InsufficientFundsException { synchronized (fromaccount) { synchronized (toaccount) { if (fromaccount.getbalance().compareto(amount) < 0) throw new InsufficientFundsException(); else { fromaccount.debit(amount); toaccount.credit(amount); Safety from race condi3ons requires some form of locking on both accounts, as shown, so that transfer will not result in funds being lost 41

42 Dynamic Lock-Ordering Deadlock public void transfermoney(account fromaccount, Account toaccount, DollarAmount amount) throws InsufficientFundsException { synchronized (fromaccount) { synchronized (toaccount) { if (fromaccount.getbalance().compareto(amount) < 0) throw new InsufficientFundsException(); else { fromaccount.debit(amount); toaccount.credit(amount); Deadlock can arise from concurrent calls: transfermoney(myaccount, youraccount, 10); transfermoney(youraccount, myaccount, 20); 42

43 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! 43

44 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 of objects value to order locks System.identityHashCode 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 (as discussed earlier) acquisition of locks may be interrupted 44

45 Dining Philosophers Problem Dijkstra, 1968 Five philosophers sit around a circular table. Each philosopher spends his life alternately thinking and ea3ng. In the centre of the table is a large bowl of spaghel. A philosopher needs two forks to eat a helping of spaghel One fork is placed between each pair of philosophers and they agree to only use the fork to his immediate right and lem 0 45

46 Dining Philosophers Problem Each fork is a shared resource with ac3ons get and put. FORK lef t phil[1]: PHIL right phil[0]: PHIL lef t FORK right phil[4]: PHIL When hungry, each PHIL must first get his right and lem forks before he can start ea3ng right lef t FORK phil[2]: PHIL right FORK lef t lef t FORK right phil[3]: PHIL 46

47 Dining Philosophers Problem class Fork { private boolean taken=false; final int iden3ty; public Fork (int i) { identity = i; synchronized void put() { taken=false; no3fy(); synchronized void get() throws java.lang.interruptedexcep3on { while (taken) wait(); taken=true; 47

48 Dining Philosophers Problem public class Philosopher extends Thread { final int identity; final Fork left; final Fork right; public Philosopher (int iden3ty, Fork lem, Fork right) { this.iden3ty = iden3ty; this.lem = lem; this.right = public void run() { // see next slide 48

49 Dining Philosophers Problem public void run() { try { while (true) { sleep(thinktime); // thinking // hungry right.get(); // got right fork lem.get(); // got left fork sleep(eattime); // ea?ng right.put(); lem.put(); catch (java.lang.interruptedexcep3on e){ 49

50 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(); 50

51 Solving The Philosophers Problem Deadlock can be avoided by ensuring that a wait-for cycle cannot exist. but how? Introduce an asymmetry into 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 51

52 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 acquisi3on by odd Philosophers Philosophers respect a protocol for lock acquisi3on 52

53 Solving The 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 the right Fork [0] before the left Fork [N-1] Any other Philosopher[i] acquires left Fork[i] before right Fork [i+1] 53

54 Recall Lock-Ordering Deadlock public void transfermoney(account fromaccount, Account toaccount, DollarAmount amount) throws InsufficientFundsException { synchronized (fromaccount) { synchronized (toaccount) { if (fromaccount.getbalance().compareto(amount) < 0) throw new InsufficientFundsException(); else { fromaccount.debit(amount); toaccount.credit(amount); transfermoney(myaccount, youraccount, 10); transfermoney(youraccount, myaccount, 20); 54

55 Ensuring Lock- Ordering The order of arguments can not 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 55

56 Ensuring Lock-Ordering public void transfermoney(account fromacct, Account toacct, DollarAmount amount) throws InsufficientFundsException { int fromhash = System.identityHashCode(fromAcct); int tohash = System.identityHashCode(toAcct); if (fromhash < tohash) { synchronized (fromacct) { synchronized (toacct) { /* do transfer */ else { synchronized (toacct) { synchronized (fromacct) { /* do transfer */ This orders lock acquisi3on according to the hash of the locks object iden3ty. This imposes a global ordering on all locks (except when they have the same hash) 56

57 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); int tohash = 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 3ed 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 bocle- neck. 57

58 Loss of Abstraction with Locks client code may wish to coordinate the synchronization of multiple objects must know which locks to use if we want to provide operations on multiple accounts, we need to know the synchronisation policy for those accounts in particular we need to know what locks are used on what methods?» what if the accounts use explicit locks instead of intrinsic monitor? how to acquire those locks? in what order should multiple locks be acquired? clients need to see some implementation details of the synchronisation policy this is a loss of abstraction it limits the reusability of code with synchronisation 58

59 Software Transactional Memory analogous to database transactions a thread optimistically completes updates of memory ignoring other threads logs reads and writes checks for conflicts with other threads at end of transaction, and commits if none if conflict occurs, transaction fails rollback is necessary with retry, or explicit alternatives provides atomicity for blocks of code nice programming model but has clear performance overheads see: 59

60 Home Work compile and run the examples on locks, deadlock and guarded methods from the Java Concurrency Tutorial newlocks.html deadlock.html guardmeth.html understand why the bounded buffer must call notifyall() and not notify() Read the javadoc for interfaces and classes defined in java.util.concurrent.locks package including the Condition class Start work on assignment 1 60

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

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions

CMSC 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 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

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

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

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

COMP 322: Fundamentals of Parallel Programming

COMP 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 information

Concurrent Programming Benoît Garbinato

Concurrent Programming Benoît Garbinato Concurrent Programming Benoît Garbinato 1 Processes & threads A process is a unit of execution managed at the level of the operating system Each process has its own address space, i.e., no other process

More information

Concurrency: Deadlock 1. Magee/Kramer 2 nd Edition

Concurrency: 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 information

Chapter 6. Deadlock Concurrency: Deadlock. Magee/Kramer 2 nd Edition

Chapter 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 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

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

Dr.-Ing. Michael Eichberg

Dr.-Ing. Michael Eichberg Dr.-Ing. Michael Eichberg Concurrent Programming (Overview of the Java concurrency model and its relationship to other models...) (some slides are based on slides by Andy Wellings) 2 Processes vs. Threads

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

Deadlock. Concepts: Models: Practice: Aim: deadlock avoidance - to design systems where deadlock cannot occur. Chapter 6. Deadlock

Deadlock. 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 information

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

Chapter 6. Deadlock. DM519 Concurrent Programming

Chapter 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 information

3C03 Concurrency: Starvation and Deadlocks

3C03 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 information

5. Liveness and Guarded Methods

5. 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 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

Dr.-Ing. Michael Eichberg

Dr.-Ing. Michael Eichberg Dr.-Ing. Michael Eichberg Concurrent Programming (Overview of the Java concurrency model and its relationship to other models...) (some slides are based on slides by Andy Wellings) Processes vs. Threads

More information

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

Summary 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 information

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects CMSC 433 Programming Language Technologies and Paradigms Composing Objects Composing Objects To build systems we often need to Create thread safe objects Compose them in ways that meet requirements while

More information

Deadlock. INF2140 Parallel Programming: Lecture 6. March 07, INF2140 Parallel Programming: Lecture 6 Deadlock

Deadlock. 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 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

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

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

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

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

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

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

Module 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 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

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

Operating Systems. Operating Systems Sina Meraji U of T

Operating Systems. Operating Systems Sina Meraji U of T Operating Systems Operating Systems Sina Meraji U of T Remember example from third week? My_work(id_t id) { /* id can be 0 or 1 */... flag[id] = true; /* indicate entering CS */ while (flag[1-id]) ;/*

More information

SFDV3006 Concurrent Programming

SFDV3006 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 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

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

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

Process Management And Synchronization

Process 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 information

Lecture 29: Java s synchronized statement

Lecture 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 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

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

Concurrency: Deadlock and Starvation. Chapter 6

Concurrency: Deadlock and Starvation. Chapter 6 Concurrency: Deadlock and Starvation Chapter 6 Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate with each other Involve conflicting needs for resources

More information

CHAPTER 6: PROCESS SYNCHRONIZATION

CHAPTER 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 information

Principles of Software Construction: Concurrency, Part 2

Principles of Software Construction: Concurrency, Part 2 Principles of Software Construction: Concurrency, Part 2 Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Homework 5a due now Homework 5 framework goals: Functionally correct Well documented

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 1018 L11 Synchronization Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Multilevel feedback queue:

More information

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

EI 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 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

CSE 153 Design of Operating Systems

CSE 153 Design of Operating Systems CSE 153 Design of Operating Systems Winter 2018 Lecture 10: Monitors Monitors A monitor is a programming language construct that controls access to shared data Synchronization code added by compiler, enforced

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Fall 2017 Lecture 11 Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Multilevel Feedback Queue: Q0, Q1,

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

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

Deadlock 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 information

From Smile To Tears: Emotional StampedLock

From Smile To Tears: Emotional StampedLock 1 From Smile To Tears: Emotional StampedLock Dr Heinz M. Kabutz Last updated 2013-11-05 From Smile to Tears: Emotional StampedLock Author of The Java Specialists' Newsletter Articles about advanced core

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Objectives Introduce Concept of Critical-Section Problem Hardware and Software Solutions of Critical-Section Problem Concept of Atomic Transaction Operating Systems CS

More information

Synchronization problems with semaphores

Synchronization 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 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 October 18, 2012 CPD (DEI / IST) Parallel and

More information

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Deadlock 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 information

Interprocess Communication By: Kaushik Vaghani

Interprocess 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 information

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs CSE 451: Operating Systems Winter 2005 Lecture 7 Synchronization Steve Gribble Synchronization Threads cooperate in multithreaded programs to share resources, access shared data structures e.g., threads

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

Concurrency 6 - Deadlock

Concurrency 6 - Deadlock Concurrency 6 - Deadlock Monitors & Condition Synchronization - Repetition!!"! "#$! %!#$ &' (&') #&' #&' # wait(), notify(), and notifyall() - Repetition public final void wait() throws InterruptedException;

More information

Process Synchronization

Process Synchronization TDDI04 Concurrent Programming, Operating Systems, and Real-time Operating Systems Process Synchronization [SGG7] Chapter 6 Copyright Notice: The lecture notes are mainly based on Silberschatz s, Galvin

More information

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking

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

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

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

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

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

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6.

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6. Part Three - Process Coordination Chapter 6: Synchronization 6.1 Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure

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

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

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Fall 2017 Lecture 12 Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ 2 Mutex vs Semaphore Mutex is binary,

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Chapter 6: Synchronization 6.1 Background 6.2 The Critical-Section Problem 6.3 Peterson s Solution 6.4 Synchronization Hardware 6.5 Mutex Locks 6.6 Semaphores 6.7 Classic

More information

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources Concurrency: Deadlock and Starvation Chapter 6 Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate with each other No efficient solution Involve conflicting

More information

CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

CSE 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 information

Lesson 6: Process Synchronization

Lesson 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 information

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

CS 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 information

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

re-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 information

Chapter 6: Synchronization. Operating System Concepts 8 th Edition,

Chapter 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 information

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Hank Levy 412 Sieg Hall

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Hank Levy 412 Sieg Hall CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization Hank Levy Levy@cs.washington.edu 412 Sieg Hall Synchronization Threads cooperate in multithreaded programs to share resources, access shared

More information

Opera&ng Systems ECE344

Opera&ng Systems ECE344 Opera&ng Systems ECE344 Lecture 6: Synchroniza&on (II) Semaphores and Monitors Ding Yuan Higher- Level Synchroniza&on We looked at using locks to provide mutual exclusion Locks work, but they have some

More information

Process Synchronization

Process 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 information

Lecture 3: Synchronization & Deadlocks

Lecture 3: Synchronization & Deadlocks Lecture 3: Synchronization & Deadlocks Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating

More information

CMSC 330: Organization of Programming Languages. Concurrency & Multiprocessing

CMSC 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 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

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Operating Systems Lecture 4 - Concurrency and Synchronization Adrien Krähenbühl Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Mutual exclusion Hardware solutions Semaphores IPC: Message passing

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

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

Teaching predicates and invariants on shared data structures in concurrent programming

Teaching predicates and invariants on shared data structures in concurrent programming Teaching predicates and invariants on shared data structures in concurrent programming Stein Gjessing Department of informatics, University of Oslo steing@ifi.uio.no Arne Maus Department of informatics,

More information

Lecture 10: Multi-Object Synchronization

Lecture 10: Multi-Object Synchronization CS 422/522 Design & Implementation of Operating Systems Lecture 10: Multi-Object Synchronization Zhong Shao Dept. of Computer Science Yale University Acknowledgement: some slides are taken from previous

More information

Operating Systems ECE344

Operating Systems ECE344 Operating Systems ECE344 Ding Yuan Announcement & Reminder Lab 0 mark posted on Piazza Great job! One problem: compilation error I fixed some for you this time, but won t do it next time Make sure you

More information

1 Process Coordination

1 Process Coordination COMP 730 (242) Class Notes Section 5: Process Coordination 1 Process Coordination Process coordination consists of synchronization and mutual exclusion, which were discussed earlier. We will now study

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

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

Lecture 10 State dependency

Lecture 10 State dependency CMSC 433 Fall 2013 Michael Hicks (Some slides due to Rance Cleaveland) Lecture 10 State dependency State- Dependent AcKons A method s behavior may depend on the current state of the object Recall the idea

More information

Multitasking / Multithreading system Supports multiple tasks

Multitasking / Multithreading system Supports multiple tasks Tasks and Intertask Communication Introduction Multitasking / Multithreading system Supports multiple tasks As we ve noted Important job in multitasking system Exchanging data between tasks Synchronizing

More information

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013 Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks

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

Liveness properties. Deadlock

Liveness 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 information

Process Synchronization

Process 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 information