Java ReentrantLock (Part 1)
|
|
- Gwen Gibson
- 5 years ago
- Views:
Transcription
1 Java ReentrantLock (Part 1) Douglas C. Schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA
2 Learning Objectives in this Part of the Lesson Understand how the concept of mutual exclusion in concurrent programs Waiting threads Critical Section Running thread See en.wikipedia.org/ wiki/mutual_exclusion 2
3 Overview of Mutual Exclusion Locks 3
4 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Critical Section See en.wikipedia.org/wiki/critical_section 4
5 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Ensures only one thread can run in a block of code at a time Critical Section 5
6 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Ensures only one thread can run in a block of code at a time Acquire lock Critical Section 6
7 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Ensures only one thread can run in a block of code at a time Critical Section Running thread 7
8 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Ensures only one thread can run in a block of code at a time Other threads are kept at bay so they don t corrupt shared resources that can be set/get by multiple concurrent operations Critical Section Waiting threads Running thread 8
9 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Ensures only one thread can run in a block of code at a time Other threads are kept at bay so they don t corrupt shared resources that can be set/get by multiple concurrent operations Race conditions could occur if multiple threads could run within a critical section Critical Section Waiting threads Running threads Race conditions can arise when a program depends on the sequence or timing of threads for it to operate properly See en.wikipedia.org/wiki/race_condition 9
10 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Ensures only one thread can run in a block of code at a time Other threads are kept at bay so they don t corrupt shared resources that can be set/get by multiple concurrent operations After a thread leaves a critical section another thread can enter & start running Critical Section Waiting threads Release lock 10
11 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Ensures only one thread can run in a block of code at a time Other threads are kept at bay so they don t corrupt shared resources that can be set/get by multiple concurrent operations After a thread leaves a critical section another thread can enter & start running Critical Section Waiting threads Acquire lock 11
12 Overview of Mutual Exclusion Locks A mutual exclusion lock (mutex) defines a critical section Ensures only one thread can run in a block of code at a time Other threads are kept at bay so they don t corrupt shared resources that can be set/get by multiple concurrent operations After a thread leaves a critical section another thread can enter & start running Critical Section Waiting threads Running thread 12
13 Overview of Mutual Exclusion Locks A mutex is typically implemented in hardware via atomic operations Atomic operations appear to occur instantaneously & either change the state of the system successful or have no effect See en.wikipedia.org/wiki/linearizability 13
14 Overview of Mutual Exclusion Locks A mutex is typically implemented in hardware via atomic operations Implemented in Java via the compareandswap*() methods in the Unsafe class See earlier discussion of Java Atomic Classes & Operations 14
15 Human Known Use of Mutual Exclusion Locks 15
16 Human Known Use of Mutual Exclusion Locks A human known use of mutual exclusion locks is an airplane restroom protocol 16
17 Human Known Use of Mutual Exclusion Locks A human known use of mutual exclusion locks is an airplane restroom protocol 17
18 Human Known Use of Mutual Exclusion Locks A human known use of mutual exclusion locks is an airplane restroom protocol lock door 18
19 Human Known Use of Mutual Exclusion Locks A human known use of mutual exclusion locks is an airplane restroom protocol lock door 19
20 Human Known Use of Mutual Exclusion Locks A human known use of mutual exclusion locks is an airplane restroom protocol unlock door This protocol is fully-bracketed, i.e., person who locks must be the same as 20 the person who unlocks
21 End of Java ReentrantLock (Part 1) 21
22 Java ReentrantLock (Part 2) Douglas C. Schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA
23 Learning Objectives in this Part of the Lesson Understand how the concept of mutual exclusion in concurrent programs Recognize how Java ReentrantLock provides mutual exclusion to concurrent programs 2
24 Overview of ReentrantLock 3
25 Provide mutual exclusion to concurrent Java programs Overview of ReentrantLock public class ReentrantLock implements Lock, java.io.serializable { See docs.oracle.com/javase/8/docs/api/java/ 4 util/concurrent/locks/reentrantlock.html
26 Provide mutual exclusion to concurrent Java programs Implements Lock interface Overview of ReentrantLock public class ReentrantLock implements Lock, java.io.serializable { See docs.oracle.com/javase/8/docs/api/ 5 java/util/concurrent/locks/lock.html
27 Applies the Bridge pattern Overview of ReentrantLock public class ReentrantLock implements Lock, java.io.serializable { Decouples its interface from its implementation so fair & non-fair semantics can be supported uniformly ReentrantLock Sync FairSync NonFairSync See en.wikipedia.org/wiki/bridge_pattern 6
28 Applies the Bridge pattern Locking handled by Sync Implementor hierarchy Overview of ReentrantLock public class ReentrantLock implements Lock, java.io.serializable { /** Performs sync mechanics */ final Sync sync; 7
29 Applies the Bridge pattern Locking handled by Sync Implementor hierarchy Inherits functionality from AbstractQueuedSynchronizer Overview of ReentrantLock public class ReentrantLock implements Lock, java.io.serializable { /** Performs sync mechanics */ final Sync sync; /** Sync implementation for ReentrantLock */ abstract static class Sync extends AbstractQueuedSynchronizer { } See docs.oracle.com/javase/8/docs/api/java/util/ 8 concurrent/locks/abstractqueuedsynchronizer.html
30 Applies the Bridge pattern Locking handled by Sync Implementor hierarchy Inherits functionality from AbstractQueuedSynchronizer Many Java synchronizers that rely on FIFO wait queues use this framework Overview of ReentrantLock public class ReentrantLock implements Lock, java.io.serializable { /** Performs sync mechanics */ final Sync sync; /** Sync implementation for ReentrantLock */ abstract static class Sync extends AbstractQueuedSynchronizer { } See gee.cs.oswego.edu/dl/papers/aqs.pdf 9
31 Applies the Bridge pattern Locking handled by Sync Implementor hierarchy Overview of ReentrantLock Inherits functionality from AbstractQueuedSynchronizer Optionally implements fair or non-fair lock acquisition model public class ReentrantLock implements Lock, java.io.serializable { public ReentrantLock (boolean fair) { sync = fair? new FairSync() : new NonfairSync(); } This param determines whether FairSync or NonfairSync is used The Reentrantlock fair & non-fair models follow 10 the same pattern used by the Java Semaphore
32 Applies the Bridge pattern Locking handled by Sync Implementor hierarchy Overview of ReentrantLock Inherits functionality from AbstractQueuedSynchronizer Optionally implements fair or non-fair lock acquisition model Ensures strict FIFO fairness, at the expense of performance public class ReentrantLock implements Lock, java.io.serializable { public ReentrantLock (boolean fair) { sync = fair? new FairSync() : new NonfairSync(); } 11
33 Applies the Bridge pattern Locking handled by Sync Implementor hierarchy Overview of ReentrantLock Inherits functionality from AbstractQueuedSynchronizer Optionally implements fair or non-fair lock acquisition model public class ReentrantLock implements Lock, java.io.serializable { public ReentrantLock (boolean fair) { sync = fair? new FairSync() : new NonfairSync(); } Enables faster performance at the expense of fairness 12
34 Applies the Bridge pattern Locking handled by Sync Implementor hierarchy Overview of ReentrantLock Inherits functionality from AbstractQueuedSynchronizer Optionally implements fair or non-fair lock acquisition model public class ReentrantLock implements Lock, java.io.serializable { public ReentrantLock (boolean fair) { sync = fair? new FairSync() : new NonfairSync(); } public ReentrantLock() { sync = new NonfairSync(); } The default behavior favors performance over fairness 13
35 Applies the Bridge pattern Locking handled by Sync Implementor hierarchy Overview of ReentrantLock Inherits functionality from AbstractQueuedSynchronizer Optionally implements fair or non-fair lock acquisition model public class ReentrantLock implements Lock, java.io.serializable { public ReentrantLock (boolean fair) { sync = fair? new FairSync() : new NonfairSync(); } public ReentrantLock() { sync = new NonfairSync(); } FairSync is generally much slower than NonfairSync, so use it accordingly 14
36 ReentrantLock is similar to the monitor lock provided by Java s built-in monitor objects Overview of ReentrantLock void void void boolean boolean lock() Acquires the lock unlock() Attempts to release this lock lockinterruptibly() Acquires the lock unless the current thread is interrupted trylock() Acquires the lock only if it is not held by another thread at the time of invocation trylock(long timeout, Timeunit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted See upcoming lessons on Java Built-in Monitor Object 15
37 ReentrantLock is similar to the monitor lock provided by Java s built-in monitor objects But also provides extended capabilities Overview of ReentrantLock void void void boolean boolean lock() Acquires the lock unlock() Attempts to release this lock lockinterruptibly() Acquires the lock unless the current thread is interrupted trylock() Acquires the lock only if it is not held by another thread at the time of invocation trylock(long timeout, Timeunit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted 16
38 ReentrantLock is similar to the monitor lock provided by Java s built-in monitor objects But also provides extended capabilities Overview of ReentrantLock void void void boolean boolean lock() Acquires the lock unlock() Attempts to release this lock lockinterruptibly() Acquires the lock unless the current thread is interrupted trylock() Acquires the lock only if it is not held by another thread at the time of invocation trylock(long timeout, Timeunit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted In contrast, Java s synchronized methods/statements are not interruptible 17
39 ReentrantLock is similar to the monitor lock provided by Java s built-in monitor objects But also provides extended capabilities Overview of ReentrantLock void void void boolean boolean lock() Acquires the lock unlock() Attempts to release this lock lockinterruptibly() Acquires the lock unless the current thread is interrupted trylock() Acquires the lock only if it is not held by another thread at the time of invocation trylock(long timeout, Timeunit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted Nor are Java s synchronized methods/statements non-blocking 18
40 Overview of ReentrantLock A ReentrantLock supports recursive mutex semantics unlocked (holdcount = 0) lock() T 1 locked (holdcount = 1) Critical Section See en.wikipedia.org/wiki/reentrant_mutex 19
41 Overview of ReentrantLock A ReentrantLock supports recursive mutex semantics The thread that hold the mutex can reacquire it without self-deadlock unlocked (holdcount = 0) lock() T 1 locked (holdcount = 1) Critical Section 20
42 Overview of ReentrantLock A ReentrantLock supports recursive mutex semantics The thread that hold the mutex can reacquire it without self-deadlock unlocked (holdcount = 0) lock() T 1 locked (holdcount = 2) Critical Section 21
43 Overview of ReentrantLock A ReentrantLock supports recursive mutex semantics The thread that hold the mutex can reacquire it without self-deadlock unlocked (holdcount = 0) lock() T 1 locked (holdcount = 2) Critical Section Recursive mutex semantics add a bit more overhead relative to nonrecursive semantics due to additional 22 software logic & synchronization
44 Overview of Key ReentrantLock Methods 23
45 Overview of Key ReentrantLock Methods It key methods acquire & release the lock public class ReentrantLock implements Lock, java.io.serializable { public void lock() { sync.lock(); } public void lockinterruptibly() throws InterruptedException { sync.acquireinterruptibly(1); } public boolean trylock() { return sync.nonfairtryacquire(1); } public void unlock() { sync.release(1); } 24
46 Overview of Key ReentrantLock Methods It key methods acquire & release the lock public class ReentrantLock implements Lock, java.io.serializable { public void lock() { sync.lock(); } public void lockinterruptibly() throws InterruptedException { sync.acquireinterruptibly(1); } public boolean trylock() { return sync.nonfairtryacquire(1); } public void unlock() { sync.release(1); } These methods are defined in the Java Lock interface 25
47 Overview of Key ReentrantLock Methods It key methods acquire & release the lock public class ReentrantLock implements Lock, java.io.serializable { public void lock() { sync.lock(); } public void lockinterruptibly() throws InterruptedException { sync.acquireinterruptibly(1); } public boolean trylock() { return sync.nonfairtryacquire(1); } public void unlock() { sync.release(1); } These methods all simply forward to their implementor methods, most 26 of which are inherited from the AbstractQueuedSynchronizer framework
48 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available public class ReentrantLock implements Lock, java.io.serializable { public void lock() { sync.lock(); } 27
49 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available If lock isn t available its implementation depends on the fairness policy public class ReentrantLock implements Lock, java.io.serializable { public void lock() { sync.lock(); } 28
50 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available If lock isn t available its implementation depends on the fairness policy Non-fair implementations are optimized in hardware public class ReentrantLock implements Lock, java.io.serializable { public void lock() { sync.lock(); } See en.wikipedia.org/wiki/spinlock 29
51 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available If lock isn t available its implementation depends on the fairness policy Non-fair implementations are optimized in hardware Fair implementations park themselves on a wait queue public class ReentrantLock implements Lock, java.io.serializable { public void lock() { sync.lock(); } 30
52 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available lockinterruptibly() acquires lock unless interrupted public class ReentrantLock implements Lock, java.io.serializable { public void lockinterruptibly() throws InterruptedException { sync.acquireinterruptibly(1); } See lesson on Managing the Java Thread Lifecycle 31
53 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available lockinterruptibly() acquires lock unless interrupted In contrast, lock() is not interruptible public class ReentrantLock implements Lock, java.io.serializable { public void lockinterruptibly() throws InterruptedException { sync.acquireinterruptibly(1); } 32
54 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available lockinterruptibly() acquires lock unless interrupted trylock() acquires lock only if it s not held by another thread at invocation time public class ReentrantLock implements Lock, java.io.serializable { public boolean trylock() { sync.nonfairtryacquire(1); } Untimed trylock() doesn t honor 33fairness setting & can barge
55 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available lockinterruptibly() acquires lock unless interrupted trylock() acquires lock only if it s not held by another thread at invocation time unlock() attempts to release the lock public class ReentrantLock implements Lock, java.io.serializable { public void unlock() { sync.release(1); } 34
56 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available lockinterruptibly() acquires lock unless interrupted trylock() acquires lock only if it s not held by another thread at invocation time unlock() attempts to release the lock public class ReentrantLock implements Lock, java.io.serializable { public void unlock() { sync.release(1); } 35
57 Overview of Key ReentrantLock Methods It key methods acquire & release the lock lock() acquires the lock if it s available lockinterruptibly() acquires lock unless interrupted trylock() acquires lock only if it s not held by another thread at invocation time unlock() attempts to release the lock IllegalMonitorStateException is thrown if calling thread doesn t hold lock public class ReentrantLock implements Lock, java.io.serializable { public void unlock() { sync.release(1); } i.e., a ReentrantLock is fully bracketed! 36
58 Overview of Other ReentrantLock Methods 37
59 Overview of Other ReentrantLock Methods There are many other ReentrantLock methods boolean trylock(long timeout, TimeUnit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted boolean isfair() Returns true if this lock has fairness set true boolean islocked() Queries if this lock is held by any thread Condition newcondition() Returns a Condition instance for use with this Lock instance These methods go above & beyond what s available 38 from Java s synchronized statements/methods
60 Overview of Other ReentrantLock Methods There are many other ReentrantLock methods boolean trylock(long timeout, TimeUnit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted boolean isfair() Returns true if this lock has fairness set true boolean islocked() Queries if this lock is held by any thread Condition newcondition() Returns a Condition instance for use with this Lock instance Timed trylock() does honor fairness setting & can t barge 39
61 Overview of Other ReentrantLock Methods There are many other ReentrantLock methods boolean trylock(long timeout, TimeUnit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted boolean isfair() Returns true if this lock has fairness set true boolean islocked() Queries if this lock is held by any thread Condition newcondition() Returns a Condition instance for use with this Lock instance 40
62 Overview of Other ReentrantLock Methods There are many other ReentrantLock methods boolean trylock(long timeout, TimeUnit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted boolean isfair() Returns true if this lock has fairness set true boolean islocked() Queries if this lock is held by any thread Condition newcondition() Returns a Condition instance for use with this Lock instance Not very useful due to non-determinism of concurrency.. 41
63 Overview of Other ReentrantLock Methods There are many other ReentrantLock methods boolean trylock(long timeout, TimeUnit unit) Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted boolean isfair() Returns true if this lock has fairness set true boolean islocked() Queries if this lock is held by any thread Condition newcondition() Returns a Condition instance for use with this Lock instance See upcoming lesson on Java ConditionObject 42
64 End of Java ReentrantLock (Part 2) 43
Java Semaphore (Part 1)
Java Semaphore (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 Objectives
More informationJava Barrier Synchronizers: CountDownLatch (Part 1)
Java Barrier Synchronizers: CountDownLatch (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,
More informationThe Java ExecutorService (Part 1)
The Java ExecutorService (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 informationJava Barrier Synchronizers: CyclicBarrier (Part 1)
Java Barrier Synchronizers: CyclicBarrier (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,
More informationJava Monitor Objects: Synchronization (Part 1)
Java Monitor Objects: Synchronization (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee,
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 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 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 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 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 informationCMSC 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 informationThe Java FutureTask. Douglas C. Schmidt
The Java FutureTask Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning Objectives
More informationOverview of Java Threads (Part 2)
Overview of Java Threads (Part 2) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Synchronization in Java Department of Computer Science University of Maryland, College Park Multithreading Overview Motivation & background Threads Creating Java
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 informationComputation 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 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 informationThe Java Executor (Part 1)
The Java Executor (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 informationBenefits of Concurrency in Java & Android: Program Structure
Benefits of Concurrency in Java & Android: Program Structure Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University
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 informationJava 8 Parallel ImageStreamGang Example (Part 3)
Java 8 Parallel ImageStreamGang Example (Part 3) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt
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 information27/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 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 informationEE458 - Embedded Systems Lecture 8 Semaphores
EE458 - Embedded Systems Lecture 8 Semaphores Outline Introduction to Semaphores Binary and Counting Semaphores Mutexes Typical Applications RTEMS Semaphores References RTC: Chapter 6 CUG: Chapter 9 1
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 informationSynchronising Threads
Synchronising Threads David Chisnall March 1, 2011 First Rule for Maintainable Concurrent Code No data may be both mutable and aliased Harder Problems Data is shared and mutable Access to it must be protected
More informationComputation 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 informationJava Threads. COMP 585 Noteset #2 1
Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the
More informationOverview of Java Threads (Part 3)
Overview of Java Threads (Part 3) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning
More informationConcurrent Queues, Monitors, and the ABA problem. Companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit
Concurrent Queues, Monitors, and the ABA problem Companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit Queues Often used as buffers between producers and consumers
More informationA Case Study of Gang of Four (GoF) Patterns : Part 7
A Case Study of Gang of Four (GoF) Patterns : Part 7 d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt University
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 informationNeed 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 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 informationDr.-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 informationOverview of Advanced Java 8 CompletableFuture Features (Part 3)
Overview of Advanced Java 8 CompletableFuture Features (Part 3) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated
More informationConcurrent Programming Lecture 10
Concurrent Programming Lecture 10 25th September 2003 Monitors & P/V Notion of a process being not runnable : implicit in much of what we have said about P/V and monitors is the notion that a process may
More informationInfrastructure Middleware (Part 1): Hardware Abstraction Layer (HAL)
Infrastructure Middleware (Part 1): Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA
More informationConcurrency Utilities: JSR-166
Concurrency Concurrency Utilities: JSR-166 Enables development of simple yet powerful multi-threaded applications > Like Collection provides rich data structure handling capability Beat C performance in
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 informationResource management. Real-Time Systems. Resource management. Resource management
Real-Time Systems Specification Implementation Verification Mutual exclusion is a general problem that exists at several levels in a real-time system. Shared resources internal to the the run-time system:
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 informationSynchronization I. Jo, Heeseung
Synchronization I Jo, Heeseung Today's Topics Synchronization problem Locks 2 Synchronization Threads cooperate in multithreaded programs To share resources, access shared data structures Also, to coordinate
More informationChapter 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 informationSSC - Concurrency and Multi-threading Advanced topics about liveness
SSC - Concurrency and Multi-threading Advanced topics about liveness Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics Review what we learned
More informationCS11 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 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 informationConcurrency: a crash course
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Concurrency: a crash course Concurrent computing Applications designed as a collection of computational units that may execute
More informationMultitasking 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 informationCOMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]
COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing
More informationInfrastructure Middleware (Part 3): Android Runtime Core & Native Libraries
Infrastructure Middleware (Part 3): Android Runtime Core & Native Libraries Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt
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 informationCS 318 Principles of Operating Systems
CS 318 Principles of Operating Systems Fall 2017 Lecture 8: Deadlock Ryan Huang Administrivia Lab 1 deadline extended - Friday 09/29 11:59 pm - Saturday 09/30 11:59 pm [Hard] HW2 out - should try to solve
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 informationModels 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 informationDr.-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 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 informationCSE 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 informationJAVA EXAMPLES - SOLVING DEADLOCK
JAVA EXAMPLES - SOLVING DEADLOCK http://www.tutorialspoint.com/javaexamples/thread_deadlock.htm Copyright tutorialspoint.com Problem Description: How to solve deadlock using thread? Solution: Following
More 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 informationLecture 9: Midterm Review
Project 1 Due at Midnight Lecture 9: Midterm Review CSE 120: Principles of Operating Systems Alex C. Snoeren Midterm Everything we ve covered is fair game Readings, lectures, homework, and Nachos Yes,
More informationCOMP346 Winter Tutorial 4 Synchronization Semaphores
COMP346 Winter 2015 Tutorial 4 Synchronization Semaphores 1 Topics Synchronization in Details Semaphores Introducing Semaphore.java 2 Synchronization What is it? An act of communication between unrelated
More informationReal-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify
http://cs.lth.se/eda040 Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify Klas Nilsson 2016-09-20 http://cs.lth.se/eda040 F4: Monitors: synchronized, wait and
More informationPOSIX Threads: a first step toward parallel programming. George Bosilca
POSIX Threads: a first step toward parallel programming George Bosilca bosilca@icl.utk.edu Process vs. Thread A process is a collection of virtual memory space, code, data, and system resources. A thread
More informationReal-Time Systems. Lecture #4. Professor Jan Jonsson. Department of Computer Science and Engineering Chalmers University of Technology
Real-Time Systems Lecture #4 Professor Jan Jonsson Department of Computer Science and Engineering Chalmers University of Technology Real-Time Systems Specification Resource management Mutual exclusion
More informationCS 450 Exam 2 Mon. 4/11/2016
CS 450 Exam 2 Mon. 4/11/2016 Name: Rules and Hints You may use one handwritten 8.5 11 cheat sheet (front and back). This is the only additional resource you may consult during this exam. No calculators.
More informationMultiple Inheritance. Computer object can be viewed as
Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.
More informationMonitors; 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 informationProgramming Paradigms for Concurrency Lecture 3 Concurrent Objects
Programming Paradigms for Concurrency Lecture 3 Concurrent Objects Based on companion slides for The Art of Multiprocessor Programming by Maurice Herlihy & Nir Shavit Modified by Thomas Wies New York University
More informationThreads and Parallelism in Java
Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program
More informationJava 8 Parallel Stream Internals (Part 2)
Java 8 Parallel Stream Internals (Part 2) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated Systems Vanderbilt
More informationMonitors; 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 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 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 informationIT 540 Operating Systems ECE519 Advanced Operating Systems
IT 540 Operating Systems ECE519 Advanced Operating Systems Prof. Dr. Hasan Hüseyin BALIK (5 th Week) (Advanced) Operating Systems 5. Concurrency: Mutual Exclusion and Synchronization 5. Outline Principles
More informationSynchronization in Java
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park Synchronization Overview Unsufficient atomicity Data races Locks Deadlock Wait /
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 informationLecture 13 Concurrent Programming
Lecture 13 Concurrent Programming 8th October 2003 Thread/Process implementation A note on terminology: process is typically (but not always) used in referring to execution contexts managed by the OS kernel.
More informationCMSC 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 informationSpinlocks. Spinlocks. Message Systems, Inc. April 8, 2011
Spinlocks Samy Al Bahra Devon H. O Dell Message Systems, Inc. April 8, 2011 Introduction Mutexes A mutex is an object which implements acquire and relinquish operations such that the execution following
More informationOperating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst
Operating Systems CMPSCI 377 Spring 2017 Mark Corner University of Massachusetts Amherst What is a Monitor? Ties data and the synchronization operations together Monitors guarantee mutual exclusion, i.e.,
More informationMultiprocessor Systems. Chapter 8, 8.1
Multiprocessor Systems Chapter 8, 8.1 1 Learning Outcomes An understanding of the structure and limits of multiprocessor hardware. An appreciation of approaches to operating system support for multiprocessor
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 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 informationCSE 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 informationConcurrency, Mutual Exclusion and Synchronization C H A P T E R 5
Concurrency, Mutual Exclusion and Synchronization C H A P T E R 5 Multiple Processes OS design is concerned with the management of processes and threads: Multiprogramming Multiprocessing Distributed processing
More informationCONCURRENT API AND PARALLEL PROGRAMMING
MODULE 11 CONCURRENT API AND PARALLEL PROGRAMMING Module 11.A THREAD MODEL: RUNNABLE, CALLABLE, FUTURE, FUTURETASK Threads > What are threads? Threads are a virtual CPU. > The three parts of at thread
More informationWhat is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem?
What is the Race Condition? And what is its solution? Race Condition: Where several processes access and manipulate the same data concurrently and the outcome of the execution depends on the particular
More informationConcurrent Processes Rab Nawaz Jadoon
Concurrent Processes Rab Nawaz Jadoon DCS COMSATS Institute of Information Technology Assistant Professor COMSATS Lahore Pakistan Operating System Concepts Concurrent Processes If more than one threads
More informationSynchronization COMPSCI 386
Synchronization COMPSCI 386 Obvious? // push an item onto the stack while (top == SIZE) ; stack[top++] = item; // pop an item off the stack while (top == 0) ; item = stack[top--]; PRODUCER CONSUMER Suppose
More informationCMSC 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 informationECE 462 Object-Oriented Programming using C++ and Java. Scheduling and Critical Section
ECE 462 Object-Oriented Programming g using C++ and Java Scheduling and Critical Section Yung-Hsiang Lu yunglu@purdue.edu d YHL Scheduling and Critical Section 1 Thread States born terminated ready running
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 informationCIS Operating Systems Application of Semaphores. Professor Qiang Zeng Spring 2018
CIS 3207 - Operating Systems Application of Semaphores Professor Qiang Zeng Spring 2018 Big picture of synchronization primitives Busy-waiting Software solutions (Dekker, Bakery, etc.) Hardware-assisted
More informationOverview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions
CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to
More information-Aditya Bhave CSCI-5448 Graduate Presentation
-Aditya Bhave CSCI-5448 Graduate Presentation 04-01-2011 MSEE at CU finishing up in Summer 11 Work full time at Alticast Inc Background in Embedded Systems Media Processing Middleware Cable TV industry
More informationCSE 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 informationCS 571 Operating Systems. Midterm Review. Angelos Stavrou, George Mason University
CS 571 Operating Systems Midterm Review Angelos Stavrou, George Mason University Class Midterm: Grading 2 Grading Midterm: 25% Theory Part 60% (1h 30m) Programming Part 40% (1h) Theory Part (Closed Books):
More informationC09: Process Synchronization
CISC 7310X C09: Process Synchronization Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/29/2018 CUNY Brooklyn College 1 Outline Race condition and critical regions The bounded
More information