Threads CS 3250 Some of these slides contain material by Professor Chuck Allison.

Slides:



Advertisements
Similar presentations
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Advertisements

Concurrency 101 Shared state. Part 1: General Concepts 2.
Understanding Java Threads Chuck Allison Utah Valley State College C/C++ Users Journal
Multithreading The objectives of this chapter are:
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.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Object-Oriented Software Engineering Concurrent Programming.
Cosc 4755 Phone programming: GUI Concepts & Threads.
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.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads CNS What is a thread?  an independent unit of execution within a process  a "lightweight process"  an independent unit of execution within.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Multithreading in Java Nelson Padua-Perez Bill Pugh 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.
Concurrency Recitation – 2/24 Nisarg Raval Slides by Prof. Landon Cox.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Lecture 4 : JAVA Thread Programming
1 Java Threads Instructor: Mainak Chaudhuri
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Internet Software Development Controlling Threads Paul J Krause.
Threading Eriq Muhammad Adams J
Copyright ©: University of Illinois CS 241 Staff1 Threads Systems Concepts.
Synchronizing threads, thread pools, etc.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
Multithreading in JAVA
Java Thread and Memory Model
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.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
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.
CMSC 330: Organization of Programming Languages Threads.
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.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
Concurrent Programming Acknowledgements: Some slides adapted from David Evans, U. Virginia.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
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.
Multithreading The objectives of this chapter are:
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Principles of Software Development
Multithreading / Concurrency
Multithreading Lec 23.
Multi-processor Scheduling
Multi Threading.
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Threads and Concurrency in Java: Part 1
Multithreading.
Multithreading.
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
Multithreading The objectives of this chapter are:
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads CS 3250 Some of these slides contain material by Professor Chuck Allison

What is a thread?  an independent unit of execution within a process  a path of execution through a program  a "lightweight process"  an independent unit of execution within a process  a path of execution through a program  a "lightweight process"

Sharing (or not)  Threads share the same address space and share the heap  + Easy to communicate with other threads  - Possibility of inconsistent states  Each thread has its own execution stack  Threads share the same address space and share the heap  + Easy to communicate with other threads  - Possibility of inconsistent states  Each thread has its own execution stack

Multi-threaded vs. Single-threaded Advantages of using more than one thread:  Single-threaded processes can't easily handle concurrent activities  e.g., waiting for user I/O, network I/O, and doing calculations at the same time  Better performance if more than one processor  No guarantees  Can sometimes get better performance even if there's only one CPU. How? Advantages of using more than one thread:  Single-threaded processes can't easily handle concurrent activities  e.g., waiting for user I/O, network I/O, and doing calculations at the same time  Better performance if more than one processor  No guarantees  Can sometimes get better performance even if there's only one CPU. How?

Multi-threaded vs. Single-threaded Disadvantages of using more than one thread:  Race conditions and deadlock  One thread can accidentally modify another's resources.  Have to deal with synchronization.  Concurrency can lead to worse performance rather than better. Disadvantages of using more than one thread:  Race conditions and deadlock  One thread can accidentally modify another's resources.  Have to deal with synchronization.  Concurrency can lead to worse performance rather than better.

Pitfalls  Watch out for libraries that aren’t thread-safe  Don’t make any assumptions about when threads will execute.  Don’t use reasoning like “that will hardly ever happen”.  Testing is necessary but not sufficient.  Test on a variety of systems.  Watch out for libraries that aren’t thread-safe  Don’t make any assumptions about when threads will execute.  Don’t use reasoning like “that will hardly ever happen”.  Testing is necessary but not sufficient.  Test on a variety of systems.

Pitfalls  Only use threads when appropriate.  “Fortunately, correct programs are frequently the simplest and have the most elegant design. Complexity should be avoided wherever possible.”  Only use threads when appropriate.  “Fortunately, correct programs are frequently the simplest and have the most elegant design. Complexity should be avoided wherever possible.” Windows System Programming, p. 223

// Illustrates Independent Threads class MyThread extends Thread { private int count; public MyThread(String name, int count) { super(name); // Optional thread name this.count = count; } public void run() { for (int i = 0; i < count; ++i) System.out.println(getName()); } A First Example Example by Professor Chuck Allison

public class Independent { public static void main(String[] args) { Thread t1 = new MyThread("DessertTopping", 8); Thread t2 = new MyThread("FloorWax", 4); t1.start(); t2.start(); } Main program launches 2 threads Define run(), call start()

DessertTopping FloorWax DessertTopping FloorWax DessertTopping FloorWax DessertTopping FloorWax DessertTopping Output (Dependent on platform and environment - YMMV)

The Runnable Interface  Alternative to extending java.lang.Thread  Declares a run( ) method  2 virtues:  Separates task from thread objects  Leaves you free to extend another class  Java only supports single inheritance  Thread has a constructor that takes a Runnable object  Alternative to extending java.lang.Thread  Declares a run( ) method  2 virtues:  Separates task from thread objects  Leaves you free to extend another class  Java only supports single inheritance  Thread has a constructor that takes a Runnable object

class MyTask implements Runnable { private int count; private String name; public MyThread(String name, int count){ this.count = count; this.name = name; } public void run(){ for (int i = 0; i < count; ++i) System.out.println(name); } The Runnable interface

public class IndependentR { public static void main(String[] args) { Thread t1 = new Thread( new MyTask("DessertTopping", 8)); Thread t2 = new Thread( new MyTask("FloorWax", 4)); t1.start(); t2.start(); } Create threads from Runnable objects

Blocking I/O  Note that the calls to println( ) run uninterrupted  I/O is a blocking operation  The thread waits until it completes  Other threads may run, but the I/O will be undisturbed  Reason: I/O is coarse-grained native code  JDK 1.4 java.nio provides non-blocking I/O  Buffers, channels, selectors, for more fine-grained control  One thread can manage multiple connections  Note that the calls to println( ) run uninterrupted  I/O is a blocking operation  The thread waits until it completes  Other threads may run, but the I/O will be undisturbed  Reason: I/O is coarse-grained native code  JDK 1.4 java.nio provides non-blocking I/O  Buffers, channels, selectors, for more fine-grained control  One thread can manage multiple connections

Interleaved I/O class MyThread extends Thread { // public void run() { for (int i = 0; i < count; ++i) { display();// Replaces println() } void display() { String s = getName(); for (int i = 0; i < s.length(); ++i) System.out.print(s.charAt(i)); System.out.println(); } Example by Professor Chuck Allison

Output (interleaved – oops!) DessertTopping DFloorWax FloorWax FloorWessertTopping Desax sertTopping DessertTopping

Race Condition result of executing program(s) depends on who runs precisely when b = getBalance(“1234”); b += 500; setBalance(“1234”, b); b = getBalance(“1234”); b -= 100; setBalance(“1234”, b); Thread 1 Thread 2 balance starts at 1000 What should the ending balance be? What will it be? Will getting rid of the local variable b solve the problem? How can we solve this problem?

Synchronization  Need to prevent race conditions  Critical region  Part of a program that accesses shared memory (or another shared resource)  To prevent race conditions, only allow one thread at a time to enter critical region  Need to prevent race conditions  Critical region  Part of a program that accesses shared memory (or another shared resource)  To prevent race conditions, only allow one thread at a time to enter critical region

Locks and Monitors  Every object has a hidden lock object  Used to protect code blocks  Monitor concept  Only allows one thread in at a time  Thread acquires a lock via some object  Other related threads wait until lock is released  Applies to all guarded methods for that object only  Achieved with the synchronized keyword  Protects code (not data directly)  Make data private!  Every object has a hidden lock object  Used to protect code blocks  Monitor concept  Only allows one thread in at a time  Thread acquires a lock via some object  Other related threads wait until lock is released  Applies to all guarded methods for that object only  Achieved with the synchronized keyword  Protects code (not data directly)  Make data private!

synchronized void f() { } How synchronized works (conceptually) Very important. Why? void f() { this.lock.acquire(); try { } finally { this.lock.release(); } is the same as the following pseudocode…

Library Example  Check-out system  Usually solved by database locks, but humor me  Book class  Must only allow one thread access to check-out check-in code  Synchronized methods  Check-out system  Usually solved by database locks, but humor me  Book class  Must only allow one thread access to check-out check-in code  Synchronized methods

// Illustrates synchronized methods class Book { private final String title; private final String author; private String borrower; public Book(String title, String author) { this.title = title; this.author = author; borrower = null; } public synchronized boolean checkOut(String borrower) { if (isAvailable()) { this.borrower = borrower; return true; } else return false; }

public synchronized boolean checkIn() { if (!isAvailable()) { borrower = null; return true; } else return false; } public String getTitle() { return title; } public String getAuthor() { return author; }

public synchronized boolean isAvailable() { return borrower == null; } public synchronized String getBorrower() { return borrower; }

Principles  Always make data private  Always protect access to shared data with a monitor (i.e., using synchronized )  Synchronize as little code as possible  Blocks instead of entire methods:  {… synchronized (obj) {…} … }  Always make data private  Always protect access to shared data with a monitor (i.e., using synchronized )  Synchronize as little code as possible  Blocks instead of entire methods:  {… synchronized (obj) {…} … }

Synchronizing display class MyThread extends Thread { private static Object lock = new Object(); // void display() { synchronized(lock) { String s = getName(); for (int i = 0; i < s.length(); ++i) System.out.print(s.charAt(i)); System.out.println(); }

DessertTopping FloorWax DessertTopping FloorWax DessertTopping FloorWax DessertTopping FloorWax DessertTopping Output (not interleaved)

A simpler way of synchronizing display synchronized static void display(String s) { for (int i = 0; i < s.length(); ++i) System.out.print(s.charAt(i)); System.out.println(); } Will use lock on class object

Threads and Exceptions  Exceptions belong to a thread  Both are stack-based  When an exception occurs in a monitor, the lock is released  For uncaught exceptions, the current thread dies  ThreadGroup.uncaughtException() is called, which prints the stack trace as its default behavior  Exceptions belong to a thread  Both are stack-based  When an exception occurs in a monitor, the lock is released  For uncaught exceptions, the current thread dies  ThreadGroup.uncaughtException() is called, which prints the stack trace as its default behavior

Deadlock  Circular wait  e.g., Breakfasting Kindergarteners, pirate map  Order access to resources  All or nothing requests for resources  Must get everything requested or nothing  Circular wait  e.g., Breakfasting Kindergarteners, pirate map  Order access to resources  All or nothing requests for resources  Must get everything requested or nothing