CSE 219 Computer Science III Multithreaded Issues.

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrency 101 Shared state. Part 1: General Concepts 2.
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.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Practice Session 7 Synchronization Liveness Guarded Methods Model
Monitors Chapter 7. The semaphore is a low-level primitive because it is unstructured. If we were to build a large system using semaphores alone, the.
CS 11 java track: lecture 7 This week: Web tutorial:
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
1 MATERI PENDUKUNG SINKRONISASI Matakuliah: M0074/PROGRAMMING II Tahun: 2005 Versi: 1/0.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
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.
Internet Software Development More stuff on Threads Paul Krause.
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.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
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.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Internet Software Development Controlling Threads Paul J Krause.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Synchronizing threads, thread pools, etc.
1 Object Oriented Programming Lecture XII Multithreading in Java, A few words about AWT and Swing, The composite design pattern.
1 G53SRP: Java Concurrency Control (1) - synchronisation Chris Greenhalgh School of Computer Science.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
CMSC 330: Organization of Programming Languages Threads.
Java Threads 11 Threading and Concurrent Programming in Java Synchronization D.W. Denbo Synchronization D.W. Denbo.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
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.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Synchronization Questions answered in this lecture: Why is synchronization necessary? What are race conditions, critical sections, and atomic operations?
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Java Thread Programming
CSCD 330 Network Programming
Multithreading / Concurrency
Multi Threading.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreaded Programming in Java
Multithreading.
Multithreading.
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Problems with Locks Andrew Whitaker CSE451.
Software Engineering and Architecture
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CSE 219 Computer Science III Multithreaded Issues

Java Thread Issues We’ve used threads naively Many things to consider when using multithreading in an application: –Swing & threads –race conditions –locking threads –deadlock

Swing & Threads NOTE: Swing is not thread-safe We have to be careful when mixing GUIs (Swing) and Concurrency (Threads) The screen should never “freeze” The program should always be responsive to user interaction –no matter what it may currently be doing

Race Conditions Threads are independent pieces of control operating on the same data. One thread could interfere with another thread’s work –results in corrupted data –called a race condition Common issue in Consumer – Producer relationships –one thread is the producer, adding to a shared data structure –one thread is the consumer, using a shared data structure 2003 Blackout problem? Race Conditions in software: – When do race conditions happen? –when transactions lack atomicity

Atomicity A property of a transaction An atomic transaction happens either completely or not at all What’s a transaction? –code execution (ex: method) that changes stored data Ex: instance variables, static variables, database

Example: A Corruptible Bank BuggedTransferer -bank:BadBank -fromAccount:int +$MAX:double +$DELAY:int +run():void BadBank -account: double[] +$INIT_BALANCE:double +$NUM_ACCOUNTS:int +transfer(from:int, to:int, double:amount):void -getTotalBalance():double > Runnable Assumptions: –We will create a single BadBank and make random transfers, each in separate threads 100 1

public class BadBank { public static int INIT_BALANCE = 1000, NUM_ACCOUNTS = 100; private double[] accounts = new double[NUM_ACCOUNTS]; public BadBank() { for (int i = 0; i < NUM_ACCOUNTS; i++) accounts[i] = INIT_BALANCE; } public void transfer(int from, int to, double amount) { if (accounts[from] < amount) return; accounts[from] -= amount; System.out.print(Thread.currentThread()); System.out.printf("%10.2f from %d to %d",amount,from,to); accounts[to] += amount; double total = getTotalBalance(); System.out.printf(" Total Balance: %10.2f%n", total); } private double getTotalBalance() { double sum = 0; for (double a : accounts) sum += a; return sum; } BadBank.java

public class BuggedTransferer implements Runnable { private BadBank bank; private int fromAccount; public static final double MAX = 1000; public static final int DELAY = 100; public BuggedTransferer(BadBank b, int from) { bank = b; fromAccount = from; } public void run() { try { while(true) { int toAccount = (int)(bank.NUM_ACCOUNTS * Math.random()); double amount = MAX * Math.random(); bank.transfer(fromAccount, toAccount, amount); Thread.sleep((int)(DELAY*Math.random())); } } catch(InterruptedException e) {/*SQUELCH*/} } BuggedTransferer.java

public class AtomiclessDriver { public static void main(String[] args) { BadBank b = new BadBank(); for (int i = 0; i < BadBank.NUM_ACCOUNTS; i++) { BuggedTransferer bT = new BuggedTransferer(b,i); Thread t = new Thread(bT); t.start(); } AtomiclessDriver.java

What results might we get? …Total Balance: …Total Balance: …Total Balance: … Why might we get invalid balance totals? race conditions operations on shared data may lack atomicity Bottom line: a method or even a single statement is not an atomic operation this means that the statement can be interrupted during its operation

A single statement? Compiled into multiple low-level statements To see: javap –c –v BadBank Ex: accounts[from] -= amount; … 21 aload_0 22 getfield #3 25 iload_1 26 dup2 27 daload 28 dload_3 29 dsub 30 dastore …

Race Condition Example Thread 1 & 2 are in transfer at the same time. Thread 1Thread 2 aload_0 getfield #3 iload_1 dup2 daload dload_3 aload_0 getfield #3 iload_1 dup2 daload dload_3 dsub dastore dsub dastore What’s the problem? This might store corrupted data

How do we guarantee atomicity? By locking methods or code blocks What is a lock? –a thread gets a lock on critical shared code –only one thread may execute locked code at a time Two techniques: 1.Locking code blocks via the ReentrantLock class new to Java in Synchronizing methods or code blocks Synchronization is easier to use, ReentrantLock with Condition classes are more powerful Can we lock an object? –yes, we’ll see how in a few moments

ReentrantLock Basic structure to lock critical code: ReentrantLock myLock = new ReentrantLock(); … myLock.lock(); try { // CRITICAL AREA TO BE ATOMICIZED } finally { myLock.unLock(); } When a thread enters this code: –if no other lock exists, it will execute the critical code –otherwise, it will wait until previous locks are unlocked

Updated transfer method public class GoodBank { private ReentrantLock bankLock = new ReentrantLock(); private double[] accounts = new double[NUM_ACCOUNTS]; … public void transfer(int from, int to, double amount) { bankLock.lock(); try { if (accounts[from] < amount) return; accounts[from] -= amount; System.out.print(Thread.currentThread()); System.out.printf("%10.2f from %d to%d",amount,from,to); accounts[to] += amount; double total = getTotalBalance(); System.out.printf(" Total Balance: %10.2f%n", total); } finally{ bankLock.unlock(); } } } NOTE: This works because transfer is the only mutator method for accounts –What if there were more than one? then we’d have to lock the accounts object

Synchronizing Methods public synchronized void deposit(int d) { … } A monitor (object with synchronized methods) allows one thread at a time to execute a synchronized method on the object –Locks the method when the synchronized method is invoked –Only one synchronized method may be active on an object at once –All other threads attempting to invoke synchronized methods must wait –When a synchronized method finishes executing, the lock on the object is released and the monitor lets the highest-priority ready thread proceed Note: Java also allows synchronized blocks of code. Ex: synchronized (this) { while (blah blah blah) blah blah blah }

Synchronized transfer method public class SynchronizedBank { … public synchronized void transfer (int from, int to, double amount) { if (accounts[from] < amount) return; accounts[from] -= amount; System.out.print(currentThread()); System.out.printf("%10.2f from %d to%d", amount,from,to); accounts[to] += amount; double total = getTotalBalance(); System.out.printf(" Total Balance: %10.2f%n", total); } } }

Locking Data synchronized is fine for locking methods, but what about data? –the synchronized keyword cannot be used on variables –Ex: the account variable to lock/unlock data we can use a combination of approaches: –use only synchronized methods for manipulating shared data OR –define a method for acquiring a lock on data –while an object is locked, make all other threads wanting to use it wait –define a method for releasing a piece (or pieces) of data, notifying all other threads when done OR –declare variables as volatile

public class GoodBank { private double[] accounts = new double[NUM_ACCOUNTS]; private boolean inUse = false; public synchronized void acquire() throws InterruptedException { while (inUse) wait(); inUse = true; notify(); } public synchronized void release() { inUse = false; notify(); } // ALL METHODS USING accounts MUST GET LOCKS FIRST Locked accounts object

// SOMEWHERE INSIDE GoodBank class acquire(); … // DO LOTS OPERATIONS THAT … // MAY MANIPULATE THE accounts … // OBJECT AS PART OF SOME … // GREATER ALGORITHM release(); Using Object Locks

wait and notifyAll wait() blocks the current thread (potentially forever) –another thread must notify it –all Object s have a wait method that can be called public synchronized void acquire() throws InterruptedException { while (inUse) wait(); inUse = true; notify(); } notify() & notifyAll() unblock a thread or all threads waiting on the current object –must be called at the end of a synchronized method, else you may get an IllegalMonitorStateException public synchronized void release(Object requestor) { inUse = false; notifyAll(); }

notify and notifyAll A thread T 1 blocked by wait() is made runnable when another thread T 2 invokes notifyAll() on the object T 1 operates on. notify() wakes up one of the waiting threads notifyAll() wakes up all waiting threads Once a thread is notified –it attempts to obtain lock again, and if successful it gets to lock all other threads out

public class GoodBank { private volatile double[] accounts = new double[NUM_ACCOUNTS]; The volatile keyword guarantees single threaded use More overhead for JVM, so slower Mixed results for use Alternative: volatile

What’s the worst kind of race condition? One that rarely happens, but causes devastating effects Hard to find, even during extensive testing Can be hard to simulate, or deliberately produce –depends on thread scheduler, which we don’t control Surface only during catastrophes Moral of the story, don’t rely on thread scheduler –make sure your program is thread safe should be determined logically, before testing

Dining Philosophers Problem 5 philosophers 5 forks 5 plates 1 large bowl of spaghetti in center

Deadlocks and other matters Deadlock: –a thread T 1 holds a lock on L 1 and wants lock L 2 AND –a thread T 2 holds a lock on L 2 and wants lock L 1. –problem: a thread holds a lock on one or more objects when it invoked wait() on itself Morals of the story: –don’t let waiting threads lock other data release all their locks before going to wait there are all sorts of proper algorithms for thread lock ordering (you’ll see if you take CSE 306) –a thread cannot be resumed if a wait is not matched by a notify