Introduction to Java Threads

Similar documents
CS11 Java. Fall Lecture 7

Mutual Exclusion using Monitors

Outline of this lecture G52CON: Concepts of Concurrency

OBJECT ORIENTED PROGRAMMING LANGUAGE

Chapter 6 Concurrent Programming

Topics. Producing Production Quality Software. Concurrent Environments. Why Use Concurrency? Models of concurrency Concurrency in Java

JAVA - MULTITHREADING

Java Memory Model: Content

Multithreaded Programming

Threads 1. When writing games you need to do more than one thing at once.

Built-in Concurrency Primitives in Java Programming Language. by Yourii Martiak and Mahir Atmis

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.

Crash Course in Java

1.1. Over view Example 1: CPU Slot Distribution A example to test the distribution of cpu slot.

Socket-based Network Communication in J2SE and J2ME

Overview Motivating Examples Interleaving Model Semantics of Correctness Testing, Debugging, and Verification

3C03 Concurrency: Condition Synchronisation

Tutorial: Getting Started

Monitors, Java, Threads and Processes

Chapter 8 Implementing FSP Models in Java

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)

Threads & Tasks: Executor Framework

Monitors (Deprecated)

Parallel Programming

Last Class: Semaphores

Concurrent programming in Java

Performance Improvement In Java Application

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Thread Synchronization and the Java Monitor

Java Concurrency Framework. Sidartha Gracias

Java Interview Questions and Answers

Java the UML Way: Integrating Object-Oriented Design and Programming

Deadlock Victim. dimanche 6 mai 12

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Fundamentals of Java Programming

Creating a Simple, Multithreaded Chat System with Java

Introducing Tetra: An Educational Parallel Programming System

Scheduling recurring tasks in Java applications

Java Virtual Machine Locks

Traditional Software Development. Model Requirements and JAVA Programs. Formal Verification & Validation. What is a state?

Unit 6: Conditions, Barriers, and RendezVous

GUI Event-Driven Programming

A Comparison of the Concurrency and Real-Time Features of Ada 95 and Java

Java TM & Real-Time Advantages, Limitations, & RTSJ

Monitors & Condition Synchronization

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

UI Performance Monitoring

MonitorExplorer: A State Exploration-Based Approach to Testing Java Monitors

Lecture 6: Introduction to Monitors and Semaphores

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

! Past few lectures: Ø Locks: provide mutual exclusion Ø Condition variables: provide conditional synchronization

An Easier Way for Cross-Platform Data Acquisition Application Development

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Semaphores and Monitors: High-level Synchronization Constructs

Building a Multi-Threaded Web Server

Monitor Object. An Object Behavioral Pattern for Concurrent Programming. Douglas C. Schmidt

Hoare-Style Monitors for Java

Manual. Programmer's Guide for Java API

Introduction to Java threads

An Overview of Java. overview-1

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Performance issues in writing Android Apps

Java SE 8 Programming

Multiprocessor Scheduling and Scheduling in Linux Kernel 2.6

Getting Started with the Internet Communications Engine

Android Application Development Course Program

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

How to develop your own app

Lecture 6: Semaphores and Monitors

BCA 421- Java. Tilak Maharashtra University. Bachelor of Computer Applications (BCA) 1. The Genesis of Java

Why Threads Are A Bad Idea (for most purposes)

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Java (12 Weeks) Introduction to Java Programming Language

Replication on Virtual Machines

4. Monitors. Monitors support data encapsulation and information hiding and are easily adapted to an object-oriented environment.

Monitors and Semaphores

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Lecture 8: Safety and Liveness Properties

CS414 SP 2007 Assignment 1

Java Coding Practices for Improved Application Performance

Homework/Program #5 Solutions

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming

Concurrent Programming

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

1 Hour, Closed Notes, Browser open to Java API docs is OK

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Better Monitors for Java

A Thread Monitoring System for Multithreaded Java Programs

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Background Tasks and Blackboard Building Blocks TM. Two great tastes that taste great together

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Inheritance, overloading and overriding

SYSTEM ecos Embedded Configurable Operating System

The Darwin Game 2.0 Programming Guide

TESTING JAVA MONITORS BY STATE SPACE EXPLORATION MONICA HERNANDEZ. Presented to the Faculty of the Graduate School of

Transcription:

Object-Oriented Programming Introduction to Java Threads 4003-243 1

What is a Process? Here s what happens when you run this Java program and launch 3 instances while monitoring with top On a single CPU architecture, the operating system manages how processes share CPU time public class MyProgram { public static void main(string args[]) { int i = 0; while ( true ) { i = i + 1; 2 process java #1 java #2 java #3 Others time

What is a Process? Besides running your program, the Java interpreter process must do other tasks Example: manage memory for your code, including garbage collection How does the interpreter perform multiple tasks within a single process? threads 3

What is a Thread? A thread is a flow of execution Java has built-in multithreading Multiple tasks run concurrently in 1 process Multiple processes and threads share CPU time Process #1 T1 T2 T3 T3 Process #2 T2 T3 T1 T4 4

Java Threads When a program executes, the JVM starts a thread to run main() This is the main thread of execution Each thread is an instance of a class that: EITHER Extends the Thread class, OR Implements the Runnable interface The new object is a runnable object Another name used is active object 5

Creating Threads by Extending Thread An example class that extends the Thread // Custom thread class public class MyThread extends Thread { public MyThread( ) { Java.lang.Thread MyThread // Override the run method // in Thread public void run() { // Run the thread // Client class public class Client { public void method( ) { // Create thread1 MyThread t1 = new MyThread( ); // Start thread1 t1.start(); // Create thread2 MyThread t2 = new MyThread( ); // Start thread2 t2.start(); 6

Creating Threads by Extending Thread A program to create and run 3 threads First thread prints the letter a 5000 times Second thread prints the letter b 5000 times Third thread prints integers 1 through 5000 Make one thread class to handle the first two threads, PrintChar The third thread will be implemented by the PrintNum class See TestThread/TestThread.java 7

Creating Threads by Implementing Runnable An active class may implement the 8 Runnable interface // Custom thread class public class MyThread implements Runnable { public MyThread( ) { Java.lang.Runnable MyThread // Override the run method // in Thread public void run() { // Run the thread // Client class public class Client { public void method( ) { // Create thread1 Thread t1 = new Thread ( new MyThread( )); // Start thread1 t1.start(); // Create thread2 Thread t2 = new Thread ( new MyThread( )); // Start thread2 t2.start();

Creating Threads by Implementing Runnable If a runnable class already inherits from a specific superclass, it must implement the Runnable interface The interface specifies one method: run() Wrap the runnable class in a Thread object to use it Thread t1 = new Thread( new PrintChar( a, 5000 ) ); Thread t2 = new Thread( new PrintChar( b, 5000 ) ); Thread t3 = new Thread( new PrintInt( 5000 ) ); See TestRunnable/TestRunnable.java 9

Thread : Selected Methods java.lang.runnable java.lang.thread Underlined methods are static 10 + Thread() + Thread(target : Runnable) + run() : void + start() : void + interrupt() : void + isalive() : boolean + setpriority(p : int) : void + join() : void + sleep(millis : long) : void + yield() : void + isinterrupted() : boolean + currentthread() : Thread

Thread Control - yield Use yield() to release the CPU See TestYield/TestYield.java T1 yields Thread #1 T1 T1 Thread #2 T2 11 T2 yields

Thread Control - sleep sleep() pauses thread execution for a specified number of milliseconds See TestSleep/TestSleep.java sleep( 500 ) Time's up. T1 wakes and runs Thread #1 T1 ZzZz waiting...zzzz... T1 T2 executes T2 stops executing Thread #2 T2 12

Thread Control - join join() makes one thread wait for another thread to finish See TestJoin/TestJoin.java T2.join() T1 resumes Thread T1 T1 T1 T2 finishes Thread T2 T2 T2 Thread has terminated Thread T3 T3 T3 13

Thread States The JVM manages thread scheduling and 14 execution using thread states Runnable is the only state in which the thread may be executing on the CPU On a single core/processor system, only one thread is actually running at any moment Other thread states record the situation of a thread with respect to its execution t.isalive() returns true if the thread is not in the New or Terminated state

Java Thread States new Thread() Block becomes unlocked Blocked Thread tries to access a locked, synchronized block New start() notify() notifyall() wait() join() sleep(t) wait(t) join(t) Runnable run() or scheduled (Running*) run() returns Terminated yield() or timeout *NOTE: Running is not an actual Thread.State enum value. It represents the thread currently executing. 15

isalive() public class WorkerThread extends Thread { private int result = 0; public void run() { // Perform a complicated, time-consuming calculation // and store the answer in the variable result public static void main(string args[]) { WorkerThread t = new WorkerThread(); t.start(); while ( t.isalive() ) { System.out.println( result ); What happens if this statement is left out? This solution works, but there is a better way! 16

Introduction to Threads Coordinating Thread Execution 17

Threads and Methods If multiple threads run inside a program, they might call the same method If they call the same method at the same time, what happens? The threads could: Read different results from member fields Overwrite field values with incorrect values To make sure only one thread executes inside a method, you must lock the object The synchronized keyword, when applied to a method, locks the object instance 18

Resource Conflict Scenario Example Situation: A program launches 100 threads, each of which adds a penny to an account Assume the account is initially empty What might happen? java.lang.thread AddAPenny 100 AccountConflict Account + run() : void 19 - bank : Account - Thread : Thread[] + main(args : String[]) : void + balance : int + getbalance() : int + deposit(amt : int) : void

Resource Conflict Scenario One thread could update the value of the common, shared balance before other(s) complete their update individually This is called a race condition A class is thread-safe if it does not cause a race condition in the presence of multiple threads 20 Step Balance Thread[ 0 ] Thread[ 1 ] In execution Actions Actions 1 0 newbalance = balance+1 2 0 newbalance = balance+1 3 1 balance = newbalance 4 1 balance = newbalance

Critical Region To avoid race conditions, program code must prevent more than one thread from executing in a critical region Code in this region may change shared state Only one thread must be allowed to enter the deposit method at a time Risky, unsynchronized version of Account.deposit(): 21 public void deposit(int amount) { int newbalance = balance + amount; balance = newbalance;

Synchronizing Instance Methods Synchronize on the account object class AddAPenny: class AddAPenny implements Runnable { public void run() { account.deposit(1); public class Account {... public synchronized void deposit(int amount) { To synchronize an instance method means a thread must get a lock on the instance before beginning to execute it Makes deposit thread-safe in Account 22

Synchronizing Instance Methods The scenario with synchronization: Thread 0 gets there first; thread 1 blocks Thread[0] Thread[1] Acquire lock on account Enter deposit Release the lock balance = 1 Blocks trying to acquire lock on account Thread[1] cannot execute here Acquires lock on account Enter deposit 23 Release the lock balance = 2

Thread Synchronization These programs illustrate and solve the resource conflict problem: 24 AccountConflict.java 100 threads add a penny to one account Lack of synchronization loses money AccountSync.java 100 threads add a penny without error A synchronized method keeps threads from corrupting the state of the Account See Synchronization/*.java

Synchronized Statements A synchronized block can lock inside a portion of a method This may shorten lock time to increase concurrency and improve performance Smaller critical region better performance 25 In AccountSync.java class Account { public void deposit( int amt ) { synchronized( this ) { int newbalance = balance + amount; Balance = newbalance;

Contention & Starvation A situation known as contention may occur when threads compete for execution time on the CPU A thread might not give other threads a chance to run That may lead to starvation What's needed are ways to make threads coordinate and cooperate with each other 26

Thread Cooperation wait(), notify() and notifyall() Three Object methods support coordination among active threads Object.wait() blocks a thread Object.notify() 'wakes up' a thread waiting on some condition Object.notifyAll() wakes up all threads waiting on some condition These methods must be called inside a synchronized method or block that has locked the object instance 27

Thread Cooperation wait(), notify() and notifyall() public final void wait() throws InterruptedException 28 Forces the thread to wait until a notify or notifyall method is called on the object If notify never happens, thread blocks forever public final void notify() Awakens one thread waiting on the object Which one wakens is implementation dependent public final void notifyall() Wakes all threads waiting on the object Scheduling decides which gets notified first

Thread Cooperation wait(), notify() and notifyall() Threads running within one process obj.wait() T1 notified and resumes Thread #1 T1 T1 obj.notify() Thread #2 T2 T2 T2 obj.wait() T3 is still waiting... Thread #3 T3 29

Threads and Interruptions A thread may be interrupted If the thread is not alive, there's no effect 30 If the thread is in the Runnable state: Set its interrupted status and move it to Blocked If the thread is Blocked: Interrupt clears the thread's interrupted status Throws an InterruptedException The thread's Blocked state has been interrupted Result: wait(), sleep() and join() calls require try { catch (InterruptedException exc) syntax

Thread Cooperation Synchronization ensures mutual exclusion 31 in critical regions to avoid race conditions Threads also need a way to cooperate without requiring threads to finish The wait/notify mechanisms can coordinate the execution of multiple threads Calls to wait(), notify() and notifyall() must be in a synchronized method or block Otherwise: IllegalMonitorStateException

Java s Monitor : A Thread Cooperation construct Two kinds of thread synchronization are: Mutual exclusion uses synchronized to keep threads from interfering with one another when sharing data Cooperation uses wait and notify to allow threads to safely coordinate and share data The structure that Java uses to support synchronization is called a monitor A monitor controls access to data and coordinates multiple threads' use of data A room where 1 thread executes at a time 32

Monitor Structure The monitor structure combines 33 synchronized, wait and notify to coordinate synchronized methoda(){ while ( condition ) { try { // Wait for condition Thread 1 executing amonitor.methoda this.wait(); catch (InterruptedException ex){ ex.printstacktrace(); // Do something critical Resumes Thread 2 executing amonitor.methodb synchronized methodb(){ // Do things // When condition is // false, then this.notify(); Or this.notifyall() to wake up all threads waiting on this amonitor

Producer-Consumer The producer-consumer threading problem is a classic in operating systems The producer creates new elements and sends them to one or more consumers A consumer takes an element out of the collection, when available, and uses it Carefully design a solution to avoid: Producer sending items that consumers miss Consumer getting the same item many times 34

Producer-Consumer See ProducerConsumer1/ ProducerConsumer2/ and ProducerConsumer3/ Producer - cubbyhole : CubbyHole - number : int + run() : void Consumer - cubbyhole : CubbyHole - number : int + run() : void CubbyHole - contents : int - available : boolean ProducerConsumerTest + main(args : String[]) : void 35 + get() : int + put() : int General structure

Consumer Waiting Behavior Name: Package: Version: Author: Consume 1 Dynamic View 1.0 BKSteele In this sequence, the consumer must wait. What happens when the producer tries to put when the cubby hole is 'not full' -- i.e. there is space to put more. theproducer :Producer 1.2 put(value) thecubby :CubbyHole 1.0 int= get() 1.1 [available == false ] wait 1.3 [available == false ] notifyall 1.4 int= get() theconsumer :Consumer When the consumer tries to get when nothing is available, the cubbyhole monitor makes the consumer's thread wait. when the producer thread comes along, it is able to immediately put in the value. Then it must notify any threads that may be waiting for that data. 1.5 notifyall 36 1.6 [available == true ] value Notification from the producer's put operation finally causes the consumer to come out of its wait and get the newly available data value. This is NOT A SECOND get() call; the thread was blocked waiting for something to notify the (consumer) thread when there is a new value available.

Producer Waiting Behavior Name: Package: Version: Author: Produce 1 Dynamic View 1.0 BKSteele theproducer :Producer thecubby :CubbyHole theconsumer :Consumer In this sequence, the producer must wait. What happens when the producer tries to put when the cubby hole is 'not full' -- i.e. there is space to put more. 1.0 put(value) 1.1 [available == true]: wait 2.1 notifyall 2.0 int= get() 2.2 value A consumer eventually comes along to get what's in the cubby and notify any waiting threads after changing the cubby's available state to false. 3.0 put(value) 3.1 [available == false] proceed to put 37 Notification from the consumer's get operation finally causes the producer to come out of its wait and put another data value into the cubby. This is NOT A SECOND put() call; the thread was blocked waiting for something to notify the (producer) thread when the cubby can accept the put of a new value.

Introduction to Threads Threads and Swing When an event occurs, how does the listener code execute? Who is executing these GUI event handlers? The short answer is: Threads 38

AWT Event Thread All GUI tasks are handled by a single thread: the AWT event dispatcher The code in a listener actually executes within the event dispatching thread AWT event thread actionperformed(actionevent e) draw a JButton 39

AWT Event Thread What code should the AWT thread run? It is good to do things in an AWT handler that cause GUI components to be redrawn AWT event thread actionperformed(actionevent e) update a text area draw a JButton 40

AWT Event Thread What if another thread has GUI work? Example: update a component Need: schedule GUI work on the main event thread or risk erroneous behavior AWT event thread user thread paint a button component update a JTextArea // ok 41 Danger: update outside the AWT event loop

AWT GUI Event Processing vs. User Processing A listener responds to events generated by a thread not running on the main event dispatching thread AWT event dispatcher may conflict with a user thread AWT event thread User thread User needs to update GUI JList dosomething() update list with data 42 Danger: update outside AWT event loop

SwingUtilities.invokeLater() To schedule a GUI interaction for the event thread, use the non-blocking call: SwingUtilities.invokeLater(Runnable task) The Runnable object s run() method performs the GUI task you want done The invokelater method queues the task object for execution later The AWT event thread will then execute it See javax.swing.swingutilities 43

SwingUtilities.invokeLater() SwingUtilities.invokeLater() is a non-blocking call SwingUtilities.invokeAndWait() blocks current thread AWT event thread user thread implementation of an operation JList dosomething () SwingUtilities.invokeLater( updatetask) 44 updatetask run() // updates JList from right place at right time

Nested and Anonymous Classes class DoIt implements Runnable { public void run() { inputdoc.remove(0, inputdoc.getlength()); SwingUtilities.invokeLater(new DoIt()); SwingUtilities.invokeLater( new Runnable() { // a class and object with no name public void run() {... inputdoc.remove(0, inputdoc.getlength());... ); // end of invokelater() call 45 Or an anonymous Runnable class can update

Nested and Anonymous Classes A nested class becomes a separate byte code file as: OuterClassName$InnerClassName.class An anonymous class file becomes a numbered.class file: OuterClassName$1.class OuterClassName$2.class 46

Exercise What happens with this code fragment? Will mythread ever run? How could you make sure mythread runs? public class ThreadQuestion { public static void main( String args[] ) { new Thread( mythread ) { public void run() { System.out.println( I m running! );.start(); 47