Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.

Slides:



Advertisements
Similar presentations
Threads, SMP, and Microkernels
Advertisements

Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Chapter 4 Threads, SMP, and Microkernels Patricia Roy Manatee Community College, Venice, FL ©2008, Prentice Hall Operating Systems: Internals and Design.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
1 Threads, SMP, and Microkernels Chapter 4. 2 Process: Some Info. Motivation for threads! Two fundamental aspects of a “process”: Resource ownership Scheduling.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 3: Processes.
1 Chapter 4 Threads Threads: Resource ownership and execution.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
A. Frank - P. Weisberg Operating Systems Introduction to Tasks/Threads.
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.
11 Other Programming Aspects Dr. Miguel A. Labrador Department of Computer Science & Engineering
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
9/13/20151 Threads ICS 240: Operating Systems –William Albritton Information and Computer Sciences Department at Leeward Community College –Original slides.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
Java Programming: Advanced Topics
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
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
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Processes and Threads Processes have two characteristics: – Resource ownership - process includes a virtual address space to hold the process image – Scheduling/execution.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
© 2004, D. J. Foreman 2-1 Concurrency, Processes and Threads.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
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.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. Concurrent programming in Java How to make all things run-able?
CS333 Intro to Operating Systems Jonathan Walpole.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
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.
1 CSCD 330 Network Programming Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 9 Client-Server Programming.
Multi-Threading in Java
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
Java Thread Programming
Processes and threads.
Multithreading Lec 23.
Multi Threading.
Java Multithreading.
CS399 New Beginnings Jonathan Walpole.
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Lecture 21 Concurrency Introduction
Multithreaded Programming in Java
Distributed Systems - Comp 655
Threads, SMP, and Microkernels
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Threads Chapter 4.
Multithreading in java.
Concurrency, Processes and Threads
Chapter 4: Threads.
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park

Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files to disk Perform useful computation (editor, browser, game) How does computer do everything at once? Multitasking Multiprocessing

Multitasking (Time-Sharing) Approach Computer does some work on a task Computer then quickly switch to next task Tasks managed by operating system (scheduler) Computer seems to work on tasks concurrently Can improve performance by reducing waiting

Multitasking Can Aid Performance Single task Two tasks

Multiprocessing (Multithreading) Approach Multiple processing units (multiprocessor) Computer works on several tasks in parallel Performance can be improved 4096 processor Cray X1 32 processor Pentium Xeon Dual-core AMD Athlon X2

Perform Multiple Tasks Using… Process Definition – executable program loaded in memory Has own address space Variables & data structures (in memory) Each process may execute a different program Communicate via operating system, files, network May contain multiple threads

Perform Multiple Tasks Using… Thread Definition – sequentially executed stream of instructions Shares address space with other threads Has own execution context Program counter, call stack (local variables) Communicate via shared access to data Multiple threads in process execute same program Also known as “lightweight process”

Web Server uses threads to handle … Multiple simultaneous web browser requests Motivation for Multithreading Captures logical structure of problem May have concurrent interacting components Can handle each component using separate thread Simplifies programming for problem Example

Multiple simultaneous web browser requests… Handled faster by multiple web servers Motivation for Multithreading Better utilize hardware resources When a thread is delayed, compute other threads Given extra hardware, compute threads in parallel Reduce overall execution time Example

Multithreading Overview Motivation & background Threads Creating Java threads Thread states Scheduling Synchronization Data races Locks Wait / Notify

Programming with Threads Concurrent programming Writing programs divided into independent tasks Tasks may be executed in parallel on multiprocessors Multithreading Executing program with multiple threads in parallel Special form of multiprocessing

Creating Threads in Java You have to specify the work you want the thread to do Define a class that implements the Runnable interface public interface Runnable { public void run(); } Put the work in the run method Create an instance of the worker class and create a thread to run it or hand the worker instance to an executor

Thread Class public class Thread { public Thread(Runnable R); // Thread  R.run() public Thread(Runnable R, String name); public void start();// begin thread execution... }

More Thread Class Methods public class Thread { … public String getName(); public void interrupt(); public boolean isAlive(); public void join(); public void setDaemon(boolean on); public void setName(String name); public void setPriority(int level); public static Thread currentThread(); public static void sleep(long milliseconds); public static void yield(); }

Creating Threads in Java Runnable interface Create object implementing Runnable interface Pass it to Thread object via Thread constructor Example public class MyT implements Runnable { public void run() { … // work for thread } Thread t = new Thread(new MyT()); // create thread t.start(); // begin running thread …// thread executing in parallel

Alternative (Not Recommended) Directly extend Thread class public class MyT extends Thread { public void run() { … // work for thread } MyT t = new MyT(); // create thread t.start();// begin running thread

Why not recommended? Not a big problem for getting started but a bad habit for industrial strength development The methods of the worker class and the Thread class get all tangled up Makes it hard to migrate to Thread Pools and other more efficient approaches

Threads – Thread States Java thread can be in one of these states New – thread allocated & waiting for start() Runnable – thread can execute Blocked – thread waiting for event (I/O, etc.) Terminated – thread finished Transitions between states caused by Invoking methods in class Thread start(), yield(), sleep() Other (external) events Scheduler, I/O, returning from run()…

Threads – Thread States State diagram runnable new terminated blocked new start terminate IO, sleep, join, request lock IO complete, sleep expired, join complete, acquire lock

Threads – Scheduling Scheduler Determines which runnable threads to run Can be based on thread priority Part of OS or Java Virtual Machine (JVM) Many computers can run multiple threads simultaneously (or nearly so)

Java Thread Example public class ThreadExample implements Runnable { public void run() { for (int i = 0; i < 3; i++) System.out.println(i); } public static void main(String[] args) { new Thread(new ThreadExample()).start(); System.out.println("Done"); }

Java Thread Example – Output Possible outputs 0,1,2,0,1,2,Done // thread 1, thread 2, main() 0,1,2,Done,0,1,2 // thread 1, main(), thread 2 Done,0,1,2,0,1,2 // main(), thread 1, thread 2 0,0,1,1,2,Done,2 // main() & threads interleaved thread 1: println 0, println 1, println 2 main (): thread 1, thread 2, println Done thread 2: println 0, println 1, println 2

Daemon Threads Why doesn’t the program quit as soon as Done is printed? Java threads types User Daemon Provide general services Typically never terminate Call setDaemon() before start() Program termination If all non-daemon threads terminate, JVM shuts down

Might not see different interleavings The threads in that example are too short Each started thread will probably complete before the next thread starts Let’s make more threads that run longer

Data Races public class DataRace implements Runnable { static volatile int x; public void run() { for (int i = 0; i < 10000; i++) { x++; x--; } public static void main(String[] args) throws Exception { Thread [] threads = new Thread[100]; for (int i = 0; i < threads.length; i++) threads[i] = new Thread(new DataRace()); for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++) threads[i].join(); System.out.println(x); // x not always 0! }

Why volatile We’ll spend more time on volatile later But volatile tells the compiler: other threads might see reads/writes of this variable don’t change/reorder eliminate the reads and writes An optimizing compiler should, if it sees x++; x--; replace it with a no-op if x isn’t volatile

Thread Scheduling Observations Order thread is selected is indeterminate Depends on scheduler, timing, chance Scheduling is not guaranteed to be fair Some schedules/interleavings can cause unexpected and bad behaviors Synchronization can be used to control thread execution order

Using Synchronization public class DataRace implements Runnable { static volatile int x; static Object lock = new Object(); public void run() { for (int i = 0; i < 10000; i++) synchronized(lock) { x++; x--; } public static void main(String[] args) throws Exception { Thread [] threads = new Thread[100]; for (int i = 0; i < threads.length; i++) threads[i] = new Thread(new DataRace()); for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++) threads[i].join(); System.out.println(x); // x always 0! }