Software Engineering and Architecture

Slides:



Advertisements
Similar presentations
Operating Systems Part III: Process Management (Process Synchronization)
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Chapter 6: Process Synchronization
5.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Chapter 5: CPU Scheduling.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
1 Race Conditions When threads share access to a common object/data, they can conflict with each other and mess up the consistency of the object/data.
CY2003 Computer Systems Lecture 05 Semaphores - Theory.
Concurrency (3) CSE 132. iClicker/WUTexter Question The following four numbers are in 8-bit 2’s complement form: Which.
Operating Systems ECE344 Ding Yuan Synchronization (I) -- Critical region and lock Lecture 5: Synchronization (I) -- Critical region and lock.
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion Tyler Robison Summer
02/23/2004CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
02/17/2010CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
02/19/2007CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
Concurrency Recitation – 2/24 Nisarg Raval Slides by Prof. Landon Cox.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Internet Software Development Controlling Threads Paul J Krause.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Chapter 6 – Process Synchronisation (Pgs 225 – 267)
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
Computer Architecture and Operating Systems CS 3230: Operating System Section Lecture OS-5 Process Synchronization Department of Computer Science and Software.
CGS 3763 Operating Systems Concepts Spring 2013 Dan C. Marinescu Office: HEC 304 Office hours: M-Wd 11: :30 AM.
CS 153 Design of Operating Systems Winter 2016 Lecture 7: Synchronization.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9 th Edition Chapter 5: Process Synchronization.
December 1, 2006©2006 Craig Zilles1 Threads & Atomic Operations in Hardware  Previously, we introduced multi-core parallelism & cache coherence —Today.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
CSCD 330 Network Programming
Interprocess Communication Race Conditions
Multithreading / Concurrency
CSE 120 Principles of Operating
Background on the need for Synchronization
Shared-Memory Concurrency & Mutual Exclusion
Atomic Operations in Hardware
Atomic Operations in Hardware
CSC Multiprocessor Programming, Spring, 2011
Chapter 5: Process Synchronization
143a discussion session week 3
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
CSE332: Data Abstractions Lecture 21: Shared-Memory Concurrency & Mutual Exclusion Dan Grossman Spring 2012.
Module 7a: Classic Synchronization
Synchronization and Semaphores
Locking in Java.
Synchronization Hank Levy 1.
Lecture 2 Part 2 Process Synchronization
Critical section problem
Race conditions and Synchronization
Background and Motivation
Dr. Mustafa Cem Kasapbaşı
Semaphores Chapter 6.
Concurrency: Mutual Exclusion and Process Synchronization
Subject : T0152 – Programming Language Concept
CSCI1600: Embedded and Real Time Software
Kernel Synchronization II
Synchronization Hank Levy 1.
CSE 153 Design of Operating Systems Winter 19
CSE 153 Design of Operating Systems Winter 2019
CS333 Intro to Operating Systems
Chapter 6: Synchronization Tools
Threads and Multithreading
CSCI1600: Embedded and Real Time Software
CSE 153 Design of Operating Systems Winter 2019
CSE 332: Concurrency and Locks
Software Engineering and Architecture
CSE 542: Operating Systems
Software Engineering and Architecture
CSE 542: Operating Systems
A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 4 Shared-Memory Concurrency & Mutual Exclusion Dan Grossman Last Updated:
Presentation transcript:

Software Engineering and Architecture Concurrency Shared Resources

Two Threads – One Account Forelæseren lønkonto PBS deposit withdraw OK CS@AU Henrik Bærbak Christensen

Two Threads – One Account Forelæseren lønkonto PBS deposit withdraw Not OK CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen Example I insert 200kr while PBS withdraws 100kr. The balance is initially 50kr. public boolean deposit(long amount){ if(amount >= 0){ return setBalance(getBalance()+amount); } else { return false; public boolean withdraw(long amount){ if(amount >= 0){ return setBalance(getBalance()-amount); } else { return false; CS@AU Henrik Bærbak Christensen

Concurrent Execution Scheduler thread switch! setBalance( 50+200 b=50 if(amount >= 0){ return setBalance(getBalance()+200 ); } else{ return false; if(amount >= 0){ return setBalance(getBalance()-100); } else{ return false; setBalance( 50+200 b=50 setBalance( 50-100 ); b=-50 ); b=250; CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen Example! The ‘System.out’ is a shared resource ! CS@AU Henrik Bærbak Christensen

Example: Shared Counter Source: http://www.javacodex.com/Concurrency/AtomicInteger-Counter CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen Race Condition Race Condition: If multiple threads writes to resources then the outcome is determined by the sequence/timing in which events occur. BAD! You have no control of the behavior of your program; and the result is erroneous Inserting 200 and withdrawing 100 on balanc 50 must be 150 Our particular execution gave 250 The next one may give -50 Critical Section: The code section in which race conditions can occur CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen The Solution Critical sections must be treated as an atomic instruction Da: ”Udelelig adgang ” That is, only one thread is allowed to be executing in a critical region at a time… Also called : Mutual exclusion CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen The Lock Guard critical regions Example: Our two threads will try to invoke deposit() and withdraw() But our account object, a, has an ”lock” associated Only one thread may acquire the lock at any time! Lecturer a PBS CS@AU Henrik Bærbak Christensen

In ‘deposit()’ a RUNNING state BLOCKED state Lecturer a PBS RUNNING state BLOCKED state The PBS thread cannot acquire the ‘lock’ and thus start executing ‘withdraw()’. It is simply put into a waiting state, and cannot continue until the lock is released! CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen Thread State Lecturer CS@AU Henrik Bærbak Christensen PBS

And next… a a Thread 1 releases lock… Now thread 2 can ‘withdraw()’ Lecturer a PBS Thread 1 releases lock… Lecturer a Now thread 2 can ‘withdraw()’ PBS CS@AU Henrik Bærbak Christensen

Monitor/Synchronized A Monitor is a class whose methods are all associated with a lock/semaphore/”lysregulering” In Java it is more fine-grained: synchronized Only methods with the synchronized keyword will respect the lock There is only one lock per object !!! Not one per method!!! CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen Synchronized Synchronized methods = whole method is a critical sect. Do not make too much code a critical section! It slows a program down if all threads have to wait for the lock Rule: Only writing needs to be guarded Rule 2: Oh yeah – and reads of items more than N bits N = 16, 32, 64 - Depending upon your processor !!! Java is portable code? CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen Synchronized Section You can simply state the object you want to sync on, on a smaller portion of the code! CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen Example again: Exercise: What should be synchronized? CS@AU Henrik Bærbak Christensen

Server Side and Client Side So far, the object itself has stated its synchronization. Often, this is not ok. Consider this ATM code: Account.debit() is synchronized What is the problem??? long available = account.getBalance(); if(available > 0){ System.out.print("You have "+available+ " available, how much do you want? "); long amount = keyboard.nextLong(); if(amount <= 0){ System.out.println("The amount must be positive."); } else if(amount > available){ System.out.println("That is too much."); else{ // This should be ok, but ... if(!account.debit(amount)){ System.out.println("The ATM debit failed!"); CS@AU Henrik Bærbak Christensen

Client Side Synchronization Syncrhonized takes the object as parameter, thus synchronized(account) { <<<ATM code here>>> } Will solve it – it is executed atomically using the lock of the account… CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen Reentrance Hey – did we not miss a thing here??? Thread starts ‘deposit()’ Acquire the lock Then calls ‘setBalance()’ But the lock is taken??? Reentrant critical sections If a thread ‘t’ has acquired the lock on object ‘a’, then it is free to invoke all other synchronized methods in ‘a’ Reentrance: The thread may reenter in locked methods Recursion ! synch public boolean deposit(long amount){ if(amount >= 0){ return setBalance(getBalance()+amount); } else { return false; CS@AU Henrik Bærbak Christensen

And – moving on…

Henrik Bærbak Christensen Java 5 Java 5 onwards introduced ‘java.util.concurrent’ because the old ‘synchronized’ was way too simple… A lot of concurrent data structures An fine-grained ‘synchronized’ Lock CS@AU Henrik Bærbak Christensen

ReentrantLock Instead of ‘synchronized’ on getCount() Note: Explicit lock object! Not on ‘this’… Can have more locks in play in same object! Ups. Uncle Bob would not be happy about this code! CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen The idiom Or tryLock(100 ms) Will time out waiting to get the lock Avoid indefinite waiting for a lock that a frozen thread has taken! Liability Code readability suffers greatly! Bjarne forgets the finally clause  lock.lock(); try { // critical region } finally { lock.unlock(); } CS@AU Henrik Bærbak Christensen

Availability AntiPattern: Blocked Threads Deadlocks Availability AntiPattern: Blocked Threads

Henrik Bærbak Christensen Deadlock Deadlock A thread waits infinitely for an event that will never happen That is T1, is in synchronized method in A, call sync. method in B T2, has acquired lock on B, and waits for lock on C … T4 waits for lock on A – which T1 has ! Result Utterly nothing!!! CS@AU Henrik Bærbak Christensen

Henrik Bærbak Christensen A Classic Edger Dijkstra, 1965: Dining Philosophers Problem Eat or think To eat you need two forks Design an algorithm that does not deadlock… [By Benjamin D. Esham / Wikimedia Commons, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=56559] CS@AU Henrik Bærbak Christensen

The General Rules of Thumb Always acquire the locks in the same order Example: A, then B, then C Only works if you know the order ahead of time Use timeouts on locks If timeout: free all locks, wait, and retry… Note – does not work for the Philosophers! CS@AU Henrik Bærbak Christensen