Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:

Slides:



Advertisements
Similar presentations
Ken Birman 1. Refresher: Dekers Algorithm Assumes two threads, numbered 0 and 1 CSEnter(int i) { int J = i^1; inside[i] = true; turn = J; while(inside[J]
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Chapter 2 Processes and Threads
Lecture 5 Concurrency and Process/Thread Synchronization     Mutual Exclusion         Dekker's Algorithm         Lamport's Bakery Algorithm.
5.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Chapter 5: CPU Scheduling.
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.
1 Java threads: synchronization. 2 Thread states 1.New: created with the new operator (not yet started) 2.Runnable: either running or ready to run 3.Blocked:
Multi-Threading Dr. M. Khamis. Thread-Based Multi-Tasking Thread-based multi-tasking is about a single program executing concurrently several tasks e.g.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Monitors CSCI 444/544 Operating Systems Fall 2008.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Process Synchronization Ch. 4.4 – Cooperating Processes Ch. 7 – Concurrency.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
CSE 219 Computer Science III Multithreaded Issues.
Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Internet Software Development Controlling Threads Paul J Krause.
1 G53SRP: Java Concurrency Control (1) - synchronisation Chris Greenhalgh School of Computer Science.
CY2003 Computer Systems Lecture 04 Interprocess Communication.
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
Java Threads 11 Threading and Concurrent Programming in Java Synchronization D.W. Denbo Synchronization D.W. Denbo.
CGS 3763 Operating Systems Concepts Spring 2013 Dan C. Marinescu Office: HEC 304 Office hours: M-Wd 11: :30 AM.
Lecture 3 Concurrency and Thread Synchronization     Mutual Exclusion         Dekker's Algorithm         Lamport's Bakery Algorithm.
Dining Philosophers & Monitors Questions answered in this lecture: How to synchronize dining philosophers? What are monitors and condition variables? What.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
1 5-High-Performance Embedded Systems using Concurrent Process (cont.)
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Linux Kernel Development Chapter 8. Kernel Synchronization Introduction Geum-Seo Koo Fri. Operating System Lab.
Threads and Swing Multithreading. Contents I. Simulation on Inserting and Removing Items in a Combo Box II. Event Dispatch Thread III. Rules for Running.
Java Thread Programming
Internationalization The Number Format Problem
CSCD 330 Network Programming
Multithreading / Concurrency
The Bouncing Ball Problem (Independent Threads)
PA1 Discussion.
Critical sections, locking, monitors, etc.
Multithreading Chapter 9.
More About Threads.
5-High-Performance Embedded Systems using Concurrent Process (cont.)
ITEC324 Principle of CS III
Monitors Chapter 7.
COT 5611 Operating Systems Design Principles Spring 2014
Dr. Mustafa Cem Kasapbaşı
Monitors Chapter 7.
Monitors Chapter 7.
CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization
NETWORK PROGRAMMING CNET 441
CSE 153 Design of Operating Systems Winter 19
Threads and Multithreading
CSCD 330 Network Programming
Software Engineering and Architecture
Chapter 9 Multithreading
Presentation transcript:

Synchronization (Threads Accessing Shared Data)

Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement: A Transfer Must Wait Until There is Sufficient Fund IV.Deadlocks

I. The Bank Transfer Problem A bank manages a number of accounts Each account has an id (integer) and a balance The bank can  Open a new account with a given initial balance  Transfer an amount from an account to another account by using the ids. Overdraft is not allowed  Provide info about the balance total of all accounts  Provide info about the number of accounts

Solution 1. The Design 2. Developing openNewAccount() 3. Developing transfer() 4. Developing getBalanceTotal() 5. Developing getNumberOfAccounts()

1. The Design

2. Developing openNewAccount()

3. Developing transfer()

4. Developing calculateBalanceTotal()

5. Developing getNumberOfAccounts()

II. Doing a Simulation on Money Transfer If there are many transfer requests, the bank must arrange several front desks to serve several customers simultaneously Create a bank that contains 100 accounts. Each account has an initial balance of $1000 Create a separate thread for each account to transfer continuously a random amount (<= $1000) to a random account, then sleep for 100 ms  Insert a rather time consuming operation, say a print() command between the withdraw() and the deposit() operations  After a transfer, print out the balance total to check if this value is the same at any time

Solution 1. Developing a Single Thread Simulator 2. Making the Single Thread Simulator to Be Mutithreading 3. Observing the Race Condition 4. Solving the Race Condition Using An Explicit Lock 5. Solving the Race Condition Using synchronized (Implicit Lock)

1. Developing a Single Thread Simulator

1.1. Create a bank with 100 accounts

1.2. For Each Account, Make Infinite Random Transfers

1.3. Make transfer() more time consuming

Run the simulator to see the first account occupies the CPU time all the time

2. Making the Single Thread Simulator to Be Mutithreading

3. Observing the Race Condition 3.1. Observe the Balance Total 3.2. The Race Condition 3.3. Explain the Race Condition in the Simulation

3.1. Observe the Balance Total

3.2. The Race Condition When multiple threads have access to the same object and each calls a method that modifies the state of the object To void this race condition, we need to synchronize the access

3.3. Explain the Race Condition in the Simulation Thread 1 wants to transfer $500 and Thread2 wants to transfer $900 to the same account

The real problem is that the work of the transfer method can be interrupted in the middle. If we could ensure that the method runs to completion before the thread loses control, then the state of the bank account object would never be corrupted.

4. Solving the Race Condition Using An Explicit Lock The basic outline for protecting a code block with a ReentrantLock is: myLock.lock();//a ReentrantLock object try { critical section } finally { myLock.unlock(); //make sure the lock is // unlock even if an exception is thrown. }

4. Solving the Race Condition Using An Explicit Lock

5. Solving the Race Condition Using synchronized (Implicit Lock) If a method is declared with the synchronized keyword, then the object's lock protects the entire method.  That is, to call the method, a thread must acquire the intrinsic object lock.

 public synchronized void method() { method body }  public void method() { this.intrinsicLock.lock(); try { method body } finally { this.intrinsicLock.unlock(); } } }

5. Solving the Race Condition Using synchronized (Implicit Lock)

III. New Requirement: A Transfer Must Wait Until There is Sufficient Fund Modify the code so that when there is not enough money in the account to transfer, it must wait until some other thread has added funds. In the mean time, it must allow other threads a chance to make a deposit Note: This requirement is just aimed to introduce Condition Objects

public void transfer(int from, int to, double amount) { lock.lock(); try { Account fromAccount = … ; while(fromAccount.canWithdraw(amount)) { // wait … } // transfer … } finally { lock.unlock(); } } Now, what do we do when there is not enough money in the account?  We wait until some other thread has added funds.  But this thread has just gained exclusive access to the lock, no other thread has a chance to make a deposit.

Solution 1. Using a Lock and a Condition 2. Using synchronized

1. Using a Lock and a Condition

If the current thread call condition.await() :  The thread is now deactivated and gives up the lock. Another thread can increase the account balance.  The thread enters a wait set for that condition. It is not made runnable. It stays deactivated until another thread has called the signalAll method on the same condition. Only one thread in the wait set is again runnable and continues where it left off. In general, a call to wait should be inside a loop while(!(ok to proceed) condition.await();

2. Using synchronized

IV. Deadlocks

Unfortunately, there is nothing in the Java programming language to avoid or break deadlocks You must design your program to ensure that a deadlock situation cannot occur

Reference Core Java, Volume I - Fundamentals, Eighth Edition, Chapter 14. Cay S. Horstmann and Gary Cornell. Prentice Hall, 2008