COMPSCI 230 S2C 2013 Software Design and Construction A Thread’s Life Lecture 2 of Theme C.

Slides:



Advertisements
Similar presentations
Multithreaded Programs in Java. Tasks and Threads A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries.
Advertisements

Concurrency 101 Shared state. Part 1: General Concepts 2.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
COMPSCI 230 S2C 2015 Software Design and Construction Thread usage and synchronisation Lecture 3 of Theme C C31.
COMPSCI 230 S2C 2013 Software Design and Construction Introduction to Java Threads Lecture 1 of Theme C.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
1 Thread Pools. 2 What’s A Thread Pool? A programming technique which we will use. A collection of threads that are created once (e.g. when server starts).
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Preventing and Correcting Errors
Threads some important concepts Simon Lynch
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
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.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
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.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Concurrent Programming and Threads Threads Blocking a User Interface.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
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.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
COMPSCI 230 S2C 2015 Software Design and Construction Synchronization (cont.) Lecture 4 of Theme C.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
Java Thread Programming
Chapter 4 – Thread Concepts
Multithreading / Concurrency
CSE 501N Fall ‘09 21: Introduction to Multithreading
Chapter 4 – Thread Concepts
Multithreaded Programming in Java
Lecture 21 Concurrency Introduction
Multithreading in Java
Multithreading Chapter 23.
Multithreading.
Cancellation.
Multithreading.
Exception Handling.
Lecture 1 Introduction to Software Construction
CMSC 202 Threads.
some important concepts
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

COMPSCI 230 S2C 2013 Software Design and Construction A Thread’s Life Lecture 2 of Theme C

Lecture Plan for Weeks /5Introduction to Java threads Sikora pp , Goetz1 pp /5A thread's lifeGoetz1 pp /5Where Java threads are used; synchronizationGoetz1 pp /5Locking, blocking, mutex; visibility, consistency.Goetz1 pp /5Deadlock; performance; programming guidelines.Goetz1 pp /5Dealing with InterruptedException (intro)Goetz2 pp /6 Executors, tasks, concurrent collections, synchronizers. Bloch pp /6Concurrency in SwingOracle 5/6 Debugging Swing / Revision of this unit Potochkin C12

Learning Goals for Today  Refine your understanding of threading:  Make a careful distinction between the support of an operating system (or a computer) for running a thread, and an instance of a Thread object in the execution of a Java program.  Understand the “lifecycle” of a thread  Start to analyse a multi-threaded application, by identifying “where” in the code the state of a thread can change state i.e. are created, become runnable, start to wait, stop waiting, and are terminated. C23

Ways to Create Threads  When a Java program is launched, it has a single thread running main().  This is called the main thread.  Any Java thread can create a new thread,  By instantiating the Thread object, or  By instantiating an object which extends Thread. C24

Java Threads and OS-supported Threads  The word “thread” is ambiguous.  It may mean an object of type Thread: this is a Java data structure.  One field in this structure is its run() method.  It may mean a locus of control in a computer system.  Goetz calls this the “actual thread”.  The operating system may provide direct support for multiple threads per process.  The JVM time-shares its OS-provided threads among its Thread objects. These objects can “come to life” only when they are paired up with an OS-supported thread.  By analogy:  a Java thread object is like a soul, and  an OS-supported thread is like a body,  in an OS-defined universe where  Souls are repeatedly incarnated in different bodies,  Souls inhabit at most one body at any given time, and  Bodies persist much longer than souls. C25

The Life-Cycle of a Thread (at “Birth”)  Instantiation (Thread.State = NEW):  A new object t of type Thread is created.  Analogy: a soul with no body. Its methods and initial state are its karma ( षन्चित कर्म ).  Any running thread can instantiate a new thread.  Inspiration (RUNNABLE for the first time):  Some running thread invokes t’s start() method.  Now t is ready to run()… but it needs a body!  Warning: if t’s inspiration occurs before its instantiation is complete, then it might start to run() before all of its instance variables are initialised. This will lead to very unpredictable – even dangerous – behaviour. The constructor method for a Thread object should not invoke this.start()!  First incarnation (actually running for the first time):  The JVM has given it a “body” (an OS thread), so it starts to execute its run() method. C26

Life-Cycle of a Thread (after birth)  After birth, Java threads are usually in one of the following states:  RUNNABLE, BLOCKED, WAITING, and TIMED WAITING.  There is a fifth state:  TERMINATED.  This state allows the garbage collector to (attempt to) reclaim any resources left behind by a thread that has exited, and which are (apparently) inaccessible to any non-TERMINATED thread.  It also allows the programmer (through the JDI) to inspect the residue of a thread, that is, the final state of its instance variables, and any resources accessible through these variables.  Thread states are adjusted by the JVM, in response to the thread’s requests and also by external events.  The Thread.getState() method will reveal a recent state of a thread –  This is stale information (especially for this.Thread.getState()), so you should not rely on it for scheduling decisions.  It is very helpful for performance-monitoring and debugging. C27

A State Diagram for Threads  : “The tutorialspoint is an absolutely FREE website which has been created to provide quality education to the people who are enthusiastic to study different technical and non-technical subjects … “So far we have come up with only few following tutorials, but it's just a beginning, and a big library comprising of various courses still needs to be created.”  This is a Petri net model for the JVM’s management of threads.  The start node is at the top: any number of tokens can be placed here.  The JVM moves a token from one place to the next, in response to the events described on the arcs. C28

Death of a Thread  It’s not a sad event… usually…  Normal termination:  A thread reaches the end of its run() method.  Abnormal termination:  A thread throws an Exception or Error that isn’t caught.  Try to catch and handle all exceptions and errors!  An abnormally terminated thread may be holding some resources that won’t be “recycled” appropriately, e.g. file handles, issued by the operating system, which may prevent other processes from accessing this file until the handle is released.  Terrible termination (deprecated):  Another thread calls stop(). (“Inherently unsafe… causes a thread to unlock all of the monitors that it has locked… ” in SE1.4/Java 2)  Another thread throws a ThreadDeath error (and this thread doesn’t catch it). C29

Joining Threads  This probably sounds like a marriage, but it’s something that happens after a thread’s death!  When a thread calls t.join(), it will block until t terminates.  This is usually understood to be an assurance that whatever t was doing in its run() is completed.  But the actual situation is more complicated…  Any external activity that t started (e.g. a disk-write) may not be completed by the time t terminates.  Any main-memory updates that t started (e.g. by writing to an unsynchronised and non-volatile object) may not be completed by the time t terminates.  Any updates that t completed (e.g. by writing to a synchronised or volatile object) before it reached the end of its run() will be complete when t.join() returns. C210

Another way to visualise threads  This is a “swim lane” diagram.  Threads start at the top.  They move downwards, sending messages to other lanes, as indicated by arrows.  A thread must wait for an incoming arrow before proceeding any farther down its path.  Object.wait() will cause a thread to wait until some other thread invokes the notify() method of this object.  Object.wait(timeout) allows a thread to proceed without a notify(), after the specified length of time. Source: TM.html TM.html C211

Learning Goals for Today  Refine your understanding of threading:  Make a careful distinction between the support of an operating system (or a computer) for running a thread, and an instance of a Thread object in the execution of a Java program.  Understand the “lifecycle” of a thread  Start to analyse a multi-threaded application, by identifying “where” in the code the state of a thread can change state i.e. are created, become runnable, start to wait, stop waiting, and are terminated. C212