CSC 480 - Multiprocessor Programming, Spring, 2012 Chapter 7 – Cancellation & Shutdown Dr. Dale E. Parson, week 9-10.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
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.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Concurrency…leading up to writing a web crawler. Web crawlers.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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).
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
More Multithreaded Programming in Java David Meredith Aalborg University.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Slides Credit Umair Javed LUMS Web Application Development.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Inter-Thread communication State dependency: Guarded Methods.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Introduction to Concurrency.
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 (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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
CS333 Intro to Operating Systems Jonathan Walpole.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
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 human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
CSC Multiprocessor Programming, Spring, 2011 Chapter 9 – GUI Applications Dr. Dale E. Parson, week 11.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSC 360, Instructor: Kui Wu Thread & PThread. CSC 360, Instructor: Kui Wu Agenda 1.What is thread? 2.User vs kernel threads 3.Thread models 4.Thread issues.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Operating Systems Unit 2: – Process Context switch Interrupt Interprocess communication – Thread Thread models Operating Systems.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
CSC Multiprocessor Programming, Spring, 2012 Chapter 10 – Avoiding Liveness Hazards Dr. Dale E. Parson, week 11.
CSC Multiprocessor Programming, Spring, 2012 Chapter 12 – Testing Concurrent Programs Dr. Dale E. Parson, week 12.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
Embedded Real-Time Systems Processing interrupts Lecturer Department University.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
Thread Pools (Worker Queues) cs
CSC Multiprocessor Programming, Spring, 2012
CSC Multiprocessor Programming, Spring, 2011
Exception Handling Chapter 9.
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Abdulmotaleb El Saddik University of Ottawa
Cancellation.
Presentation transcript:

CSC Multiprocessor Programming, Spring, 2012 Chapter 7 – Cancellation & Shutdown Dr. Dale E. Parson, week 9-10

Task cancellation Activity is cancellable if external code can move it to completion before normal completion. (p. 135) Server or similar non-terminating activity. Long-running computation. Cancellable implies asynchronous notification. – User-requested cancellation. – Time-limited activities. – Application events (e.g., first solution stops others). – Errors (e.g., file server backing database goes off line). – Shutdown.

Interruption Thread.currentThread() gets current thread. interrupt() interrupts a thread object. Asynchronous but not preemptive. isInterrupted() returns some thread’s status without changing it. Thread.interrupted() returns current thread’s interrupt status and clears it. InterruptedException thrown by many blocking methods. Thrower may clear interrupted status.

Interruption for cancellation Calling interrupt() merely delivers a message. Using interruption for anything but cancellation is fragile and difficult to sustain in larger applications. (p. 138) Interruption is usually the most sensible way to implement cancellation. (p. 140) The intent is that threads running application tasks will have periodic opportunities to notice the interruption message, and know what that means.

Cancellation & Interruption Policy A Cancellation Policy is a plan for how an algorithm quits in the middle of its work. An Interruption Policy is a plan for how application threads and tasks respond to interrupt messages. Interruption is ultimately under the control of the application framework. The design of an application framework must establish how it uses interrupts to communicate with tasks.

Responding to an interrupt Do not interrupt() a thread unless you know its interruption policy. Interruption typically comes from elsewhere in application code. Library and application-neutral framework code may neither interpret nor ignore InterruptedException. A library method may throw the InterruptedException. A library method may re-call interrupt() on its thread. Application code must handle the interrupt. Use the cancellation and interruption policy to direct control. Swallow InterruptedException only if that works with the policies.

Task Cancellation Tasks run in frameworks, e.g., ExecutorService. submit() returns a Future; it may be cancel()d. cancel() has mayInterruptIfRunning param. The application-level task, if running, must decide what to do with the optional interrupt. Future.get throws CancellationException or ExecutionException for abnormal termination of its task. Latter carries its original cause.

Uninterruptible I/O InputStream.read and OutputStream.write do not throw InterruptedException. Calls may block indefinitely. close() on the underlying stream from another thread causes IOException, but it may be dangerous. Sending a “Poison pill” (special sentinel value) into the stream from another thread, if possible, is safer. java.nio and java.nio.channels.Selectors have related issues, also support for closed-by-interrupt exceptions. See Javadoc.

Uninterruptible lock acquisition Explicit lock has lockInterruptibly(), but lock() and implicit synchronized locks are uninterruptible. If there is no cyclic dependency among locks (which leads to deadlock), the thread holding the lock must make progress, possibly via interruption, and release the lock. Compute-bound tasks or tasks that invoke non- interruptible methods, and that have an interruption policy, may need to poll isInterrupted() periodically.

Stopping a thread-based service Lifecycle methods of the service are necessary for state transitions and termination. The thread pool that manages the worker threads decides whether and when to interrupt them. The application code running in the service threads decides how to respond to interruption (policy). ExecutorService.shutdown shutdown() – previously submitted tasks are executed, but no new submissions are accepted. shutdownNow() attempts to terminate tasks (typically via interrupt()) and returns a list of tasks that were awaiting execution.

Poison pill Poison pill is a sentinel value that a producer passes to consumer(s) to signal shutdown. Poison pill(s) must come after all regular producer application data. From solution #1 Input.run(): if (myburst.isEmpty()) { int remaining = pktq.decrementAndGetInputs(); if (remaining == 0) { // I was the last Input thread, send a sentinel to each // output thread. int outputcount = pktq.getOutputs(); for (int i = 0 ; i < outputcount ; i++) { pktq.enqueue(myburst); // empty list is sentinel } return ; }

Limitations of shutdownNow There is no option to cancel un-started tasks while allowing started tasks to complete. It is possible to extend or adapt ExecutorService to interact with tasks in an application-specific way to determine which tasks are started without completion, and to stop only the unstarted ones. See Race condition at task completion time is still likely.

Abnormal thread termination Possible to log a stack trace, but general purpose thread pool library classes do not own the application logs. Printing stack traces to System.err may be lost. General purpose framework (e.g., Eclipse) may catch unchecked exceptions (RuntimeException) and display a warning about the suspect integrity of the compromised application task or plug-in.

Boilerplate code for dealing with untrusted tasks (p. 162) public void run() { Throwable thrown = null ; try { while (! currentThread().isInterrupted()) { runTask(getTaskFromWorkQueue()); } } catch (Throwable e) { thrown = e ; } finally { threadExited(this, thrown); }}

JVM shutdown and Daemon threads Runtime.addShutdownHook() deals with cases where a thread invokes System.exit() or a terminating signal arrives from the O.S. It starts a series of registered threads. Make these thread-safe, defensive, and conservative. Daemon threads are never joined to the main thread. Text advises to use them sparing, perform no I/O in them. Use them for housekeeping such as managing an in-memory cache.

Finalizers Object.finalize() runs when the garbage collector is about to recover an object. Test says: “Avoid finalizers.” Explicit try-finally blocks that close() (and flush) output resources are safer and easier than using finalizers. They may be necessary for freeing resources obtained by native methods.