2006-08-02 Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.

Slides:



Advertisements
Similar presentations
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
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.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Designing a thread-safe class  Store all states in public static fields  Verifying thread safety is hard  Modifications to the program hard  Design.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Concurrency CS 510: Programming Languages David Walker.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
ThreadThread Thread Basics Thread Synchronization Animations.
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 in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
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.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
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.
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.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
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.
 2004 Deitel & Associates, Inc. All rights reserved. 1 Chapter 4 – Thread Concepts Outline 4.1 Introduction 4.2Definition of Thread 4.3Motivation for.
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.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Chapter 2 Processes and Threads Introduction 2.2 Processes A Process is the execution of a Program More specifically… – A process is a program.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
© Wang Bin 2004 Java Threads. © Wang Bin 2004 In this lesson, you will learn to: u Define the concepts of threads and multithreading  Identify the functions.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
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.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
Java Thread Programming
Multithreading The objectives of this chapter are:
Chapter 4 – Thread Concepts
Multithreading / Concurrency
Multi Threading.
Chapter 4 – Thread Concepts
Multithreaded Programming in Java
Multithreading Chapter 9.
Lecture 21 Concurrency Introduction
More About Threads.
Lecture 7 Processes and Threads.
Multithreading.
Threads Chapter 4.
Threads and Multithreading
Concurrent programming
Multithreading The objectives of this chapter are:
More concurrency issues
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo

Java Threads2 Overview We will be covering both the tools, classes and interfaces available within JDK 5.0, and the concepts necessary to develop robust multithreaded applications. Multithreading is necessary to create applications, both GUI and client-server, that are both responsive to the user and provide a high level of control. We will be covering both the tools, classes and interfaces available within JDK 5.0, and the concepts necessary to develop robust multithreaded applications. Multithreading is necessary to create applications, both GUI and client-server, that are both responsive to the user and provide a high level of control.

Java Threads3 Outline What are Threads? Advantages Limitations Java concurrency support Interrupting Threads Thread States What are Threads? Advantages Limitations Java concurrency support Interrupting Threads Thread States

Java Threads4 What are Threads? A thread, short for thread of control, enables multitasking within a single program. While processes has a complete set of its own variables, threads share the same data. Multithreading changed dramatically in JDK 5.0, with the addition of a large number of specialty classes and interfaces that support threading. Warning: multithreading can get very complex! A thread, short for thread of control, enables multitasking within a single program. While processes has a complete set of its own variables, threads share the same data. Multithreading changed dramatically in JDK 5.0, with the addition of a large number of specialty classes and interfaces that support threading. Warning: multithreading can get very complex!

Java Threads5 Advantages Reactive programming Availability Controllability Active objects Asynchronous messages Parallelism Required concurrency Reactive programming Availability Controllability Active objects Asynchronous messages Parallelism Required concurrency

Java Threads6 Reactive Programming Some programs are required to do more than one thing at a time. While it is possible to program such systems in a single-threaded manner by manually interleaving the different activities, this is complicated, fragile, and error-prone. Reactive programs are easier to design and implement using threads.

Java Threads7 Availability Concurrency allows you to maintain high availability of services. For example, you can have one object serve as a gateway interface to a service, handling each request by constructing a new thread to asynchronously perform the associated

Java Threads8 Controllability Activities can be suspended, resumed, and stopped by other objects. (NOTE: don’t use the stop, suspend, or resume methods.) This is done by setting flags or raising exceptions within the thread.

Java Threads9 Active Objects Software objects often model read objects. Most real objects display independent, autonomous behavior.

Java Threads10 Asynchronous Messages When one object sends a message to another, the sender doesn’t always care when the resulting action is performed. Threads allow the first object to continue its own activity without waiting.

Java Threads11 Parallelism Multiple CPUs can be can be used to exploit available computing power. Even without multiple CPUs, interleaving activities in threads avoids delays, for example, waiting for remote connection and data transfer.

Java Threads12 Required Concurrency Some Java features require threaded applications. For example, audio clips and proper updating of graphics during animations and status information updating.

Java Threads13 Limitations Safety Liveness Nondeterminism Threads versus method calls Objects versus activities Thread construction overhead Context-switching overhead Synchronization overhead Threads versus processes Safety Liveness Nondeterminism Threads versus method calls Objects versus activities Thread construction overhead Context-switching overhead Synchronization overhead Threads versus processes

Java Threads14 Safety When multiple threads are not completely independent, each can be involved in sending messages to other objects that may also be involved in other threads. These objects must use synchronization mechanisms to maintain consistent state. Using multiple threads involving objects designed to work only in sequential settings can lead to hard to debug inconsistencies.

Java Threads15 Liveness Activities within concurrent programs may fail to be live. One or more activities can simply stop for any number of reasons, for example, deadlocking, resource limitations, and uncaught exceptions.

Java Threads16 Nondeterminism Multithreaded activities can be arbitrarily interleaved. No two executions of the same program need be identical.

Java Threads17 Threads versus Method Calls Threads are not very useful for request/reply- style programming. When one object must logically wait for a reply from another in order to continue, the same thread should be used to implement the entrire request- execute-reply sequence.

Java Threads18 Objects versus Activities There are many fewer asynchronously executing concurrent activities than objects. It makes sense to create a new thread only when an invocation actually generates a new asynchronous activity, not automatically whenever constructing a new object that may or may not engage in asynchronous activities.

Java Threads19 Thread Construction Overhead Constructing a thread and setting it in motion is typically slower and more memory- intensive than constructing a normal object or invoking a method on it. If an activity is short, then it is much faster to just invoke it rather than to use threads.

Java Threads20 Context-switching Overhead When there are more active threads than there are CPUs, the Java run-time system occasionally switches from running one activity to running another, which also entails scheduling -- figuring out witch thread to run next.

Java Threads21 Synchronization Overhead Java methods employing synchronizations can be slower than those that do not provide proper concurrency protection. Between thread and synchronization overhead, concurrent programs can run more slowly than sequential ones.

Java Threads22 Threads versus Processes Activities that are intrinsically self-contained and sufficiently heavy may be simpler to encapsulate into standalone programs. Standalone programs can be accessed via system-level execution facilities ore remote invocation mechanisms rather than as multithreaded components of a single process.

Java Threads23 JDK 5.0 Concurrency Support Java.lang.Thread Keywords - synchronized and volatile Methods - wait, notify, and notifyAll Blocking Queues Thread-safe collections Callables and Futures Executors Synchronizers Java.lang.Thread Keywords - synchronized and volatile Methods - wait, notify, and notifyAll Blocking Queues Thread-safe collections Callables and Futures Executors Synchronizers

Java Threads24 Interrupting Threads A thread terminates when its run method returns. In JDK 1.0, there also was a stop method, however, that method is now deprecated. There is no longer a way to force a thread to terminate. However, the interrupt method can be used to request termination of a thread. A thread terminates when its run method returns. In JDK 1.0, there also was a stop method, however, that method is now deprecated. There is no longer a way to force a thread to terminate. However, the interrupt method can be used to request termination of a thread.

Java Threads25 while (!Thread.currentThread().isInterrupted()) { // do more work } However, if a thread is blocked, it cannot check the interrupted status. This is where the InterruptedException is used. while (!Thread.currentThread().isInterrupted()) { // do more work } However, if a thread is blocked, it cannot check the interrupted status. This is where the InterruptedException is used.

Java Threads26 public void run() { try { while(!Thread.currentThread().isInterrupted()) { // do more work } } catch(InterruptedException ie) { // thread was interrupted during sleep or wait }finally { // cleanup, if required } // exiting the run method terminates the thread } public void run() { try { while(!Thread.currentThread().isInterrupted()) { // do more work } } catch(InterruptedException ie) { // thread was interrupted during sleep or wait }finally { // cleanup, if required } // exiting the run method terminates the thread }

Java Threads27 Thread States New - When a thread is created with the new operator - the thread is not yet running. It is in the new state. Runnable - Once the start method has been invoked the thread is runnable. New - When a thread is created with the new operator - the thread is not yet running. It is in the new state. Runnable - Once the start method has been invoked the thread is runnable.

Java Threads28 Thread States (cont) Blocked - A thread enters the blocked state: By calling the sleep method Thread calls an operations that is blocking on I/O Thread tries to acquire a lock Thread waits for a condition Suspend method is invoked. (deprecated) Blocked - A thread enters the blocked state: By calling the sleep method Thread calls an operations that is blocking on I/O Thread tries to acquire a lock Thread waits for a condition Suspend method is invoked. (deprecated)

Java Threads29 Thread States (cont) Dead - a thread is dead when It dies a natural death because the run method exits normally. It dies abruptly because of an uncaught exception. Dead - a thread is dead when It dies a natural death because the run method exits normally. It dies abruptly because of an uncaught exception.