1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Multithreading Horstmann ch.9. Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library.
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
Synchronization in Java Nelson Padua-Perez Bill Pugh 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.
ThreadThread Thread Basics Thread Synchronization Animations.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
Definitions Process – An executing program
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
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.
Java Programming: Advanced Topics
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.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
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.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
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.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Multi-Threading in Java
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
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.
1 Dr.A.Srinivas PES Institute of Technology Bangalore, India
CMSC 330: Organization of Programming Languages Threads.
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.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
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.
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.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
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 (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
Multithreading / Concurrency
Multi Threading.
Multithreading.
Multithreading Chapter 9.
Threads Chate Patanothai.
Multithreading.
Java Based Techhnology
Multithreading.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Threads and Multithreading
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County

2 Concurrent Programming Running tasks in parallel Multiple processes Multiple threads in one process? Advantage: speed if you can decompose a task into parallel independent tasks Examples Webserver: multiple requests to cater to. Web browser: multiple objects loading simultaneously Encoding multiple blocks simultaneously Almost everything today can be broken into parallel tasks.

3 Threads and running processes

4 Creating Threads: extend the Thread class Thread is a basic class which provides two methods void start() Creates a new thread and makes it runnable void run() A new Thread begins its life inside this method public class A extends Thread { public A() { … constructor…} public void run() {…method that will run in the thread….} }

5 Lets take a concrete example in eclipse Application: Provide parallel addition Input: array of integers a[1,…,k] Divide array into segments and in parallel add segments of the array For example: Thread 1: add a[1:k/2] Theads 2: add a[k/2:k] Add both of them together

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

Thread Creation Diagram Thread t = new BThread(); t.start(); doMoreStuff(); Object A BThread() { } void start() { // create thread } void run() { doSomething(); } Object BThread (extends Thread)

15 Another way of creating Threads: Runnable interface A helper to the thread object Your class implements the Runnable interface The Thread object’s run() method calls the Runnable object’s run() method Allows threads to run inside any object, regardless of inheritance

16 Example of using the Runnable interface public class MyRunnable implements Runnable { String name; public MyRunnable(String name) { this.name = name; } public void run() { for(int i; i < 10; i++) { System.out.println(i + “ “ + name()); try { sleep((long)(Math.random() * 1000)); } catch(InterruptedException e) {} } public class ThreadTest { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { Thread t = new Thread(new MyRunnable(args[i]), args[i]); t.start(); }

Blocking Threads When reading from a stream, if input is not available, the thread will block Thread is suspended (“blocked”) until I/O is available Allows other threads to automatically activate When I/O available, thread wakes back up again – Becomes “runnable” – Not to be confused with the Runnable interface

Thread Scheduling In general, the runnable thread with the highest priority is active (running) Java is priority-preemptive – If a high-priority thread wakes up, and a low-priority thread is running – Then the high-priority thread gets to run immediately Allows on-demand processing – Efficient use of CPU

Thread Starvation If a high priority thread never blocks Then all other threads will starve Must be clever about thread priority

Thread Priorities: General Strategies Threads that have more to do should get lower priority Counterintuitive Cut to head of line for short tasks Give your I/O-bound threads high priority – Wake up, immediately process data, go back to waiting for I/O

Thread interruption Threads execution exits when the run() method returns Or if it throws an exception that is not handled in the run() method What if you want to interrupt a running Thread? Thread.interrupt() --- call interrupts a Thread – Sets a interrupt flag for the Thread object! – How does a Thread check whether the flag is checked? – Thread.currentThread.isInterrupted()?

Example while (!Thread.currentThread().isInterrupted()) { …do something ….} What if the Thread is sleeping or blocked? Solution: catch InterruptedException? try { while(!Thread.currentThread.isInterrupted()) {..do something…} catch(InterruptedException e) { //thread interrupted during sleep or wait} When interrupted, interrupt flag is set and the Thread is woken up!

Race Conditions Two threads are simultaneously modifying a single object Both threads “race” to store their value In the end, the last one there “wins the race” (Actually, both lose)

Race Condition Example Lets take an example in eclipse to illustrate this

25 Race condition explained… What is the shared object in our example? the Bank object?? Accessing shared objects is also termed as accessing “critical sections” of data Lets look at a statement in the critical section. account[to] += amount;

26 Race condition explained.. Lets decompose the previous statement into assembly and see what it constitutes.. Load accounts[to] to some register Add amount to that register Copy back the result into the memory location The problem is that the above three statements are not atomic (Atomic operation is something that cannot be preempted) Lets see what can potentially happen when two threads simultaneously access this statement…

27 Race condition explained… Load X R1 Add Y Z R1 Store Y in Mem Thread 1 executes the first two statements and is preempted… Thread 2 executes all the three statements Thread 1 returns and executes the third statement What has happened here?

28 Intuitively how would you solve this problem… First solution: allow only one thread to access the “critical section” or “shared object” at one time!!!! Easiest way of doing this is using locks… java.util.concurrent provides the Lock interface and ReentrantLock implementation Lock myLock = new ReentrantLock(); myLock.lock(); //acquire a lock.. try { critical section….. } catch(Exception e) {} myLock.unlock() //give up the lock

29 Properties of locks… Only one Thread can acquire a lock at one time Suppose one Thread acquires the lock Second Thread tries to acquire it Second Thread blocks till first Thread releases the lock Make sure every lock is accompanied by an unlock statement Else things will block forever  Reentrant means the same Thread can acquire the lock multiple times In our example every Bank object has a separate lock… For different Bank objects the locks are completely different.. They do not collide…

30 Condition objects! Lets refine our Bank example Add a condition that you can transfer money only if there is sufficient balance Unsynchronized way of doing it if(accounts[from] > amount) { carry out the transfer…} Problem If(accounts[from] > amount) { Thread preempted… Some other thread removes the money from the account Thread scheduled again.. //now the operation is just WRONG!!! }

31 Lets see if we can use locking to solve this mylock.lock(); while(account[from] < amount){ Thread.sleep(100); } //do the transfer… mylock.unlock(); What is the problem here? Only one Thread can acquire the lock.. This might lead to a deadlock…

32 Java’s conditional variables Java provides Conditional variables with every Lock How do you use it:: Using a conditional (you can declare as many as you want) private Lock myLock = new ReentrantLock(); public Bank() { //constructor private Condition sufficientFunds = myLock.newCondition();} myLock.lock(); while(accounts[from] < amount) { sufficientFunds.await(); // } //Transfer funds.. sufficientFunds.signalAll(); myLock.unlock();

33 Lets take a closer look at the await() and signalAll() sufficientFunds.await() It pulls the Thread out of the run queue and places it in a condition queue (specific to that particular condition) Releases the lock that the thread was holding Consequently other Threads that are blocked on that lock can get the CPU!!! sufficientFunds.signalAll() Signals all the Threads that are waiting on that particular condition Indication that condition (sufficientFunds) in our case in now satisfied… The Thread can be scheduled if it has the lock.

34 Difference between conditional wait and waiting on a lock Condition Queue 1 Condition Queue 2 CPU Blocked on lock Wait on a lock unlock Run Condition.await() Condition.signalAll()

35 Summary of locking and conditional A lock protects a section of code, allowing only one thread to access the critical section at one time A lock manages threads that are trying to enter this “protected” code segment A lock can have more than one conditional objects associated with it Each conditional object manages threads that have entered a protected code section but cannot proceed due to a “condition”.

36 The synchronized keyword! Locks and Conditions provide you with fine-grained synchronization However there is an easier way of synchronizing object if you are ready to sacrifice some of the flexibility The Java language provides a keyword “synchronized” that can be used to make a method thread-safe Every Java object has an intrinsic lock Calling a method synchronized uses that intrinsic lock Lets take an example //In Bank.java public synchronized void transfer() { … method body…. }..

37 Take a close look at the synchronized method public synchronized void transfer() { ….method body….. } public void transfer() { this.intrinsicLock.lock(); // acquire the intrinsic lock ….method body….. this.intrinsicLock.unlock() //release the instrinsic lock } Equivalent to the following

Thread Lifecycle Born Blocked Runnable Dead stop() start() stop() Active block on I/O I/O available JVM sleep(500) wake up suspend() resume() wait notify