Concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors,

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

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Yoshi
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling Exception handling (EH) allows a programmer to provide code in the program to handle run-time errors or exceptional situations – this.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 13 In a language without exception handling: When an exception occurs, control goes to the operating.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Exceptions (Large parts of these copied from Ed Schonberg’s slides)
Concurrency in Ada What concurrency is all about Relation to operating systems Language facilities vs library packages POSIX threads Ada concurrency Real.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors,
Concurrency CS 510: Programming Languages David Walker.
Concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors,
Concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors,
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
1 Exceptions and Concurrency Exceptions and Concurrency.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
Comparative Programming Languages hussein suleman uct csc304s 2003.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
May 21, ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)
Object Oriented Programming
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
12/1/98 COP 4020 Programming Languages Parallel Programming in Ada and Java Gregory A. Riccardi Department of Computer Science Florida State University.
Compiler Construction
(12.1) COEN Concurrency and Exceptions  Coroutines  Physical and logical concurrency  Synchronization – semaphores – monitors – message passing.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
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.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
CS212: Object Oriented Analysis and Design Lecture 20: Exception Handling-II.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Java Exceptions a quick review….
Introduction to Exceptions in Java
Why exception handling in C++?
Multithreaded Programming
Exception and Event Handling
Exception Handling.
Presentation transcript:

concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors, other illegalities User-defined exceptions for robust abstractions Predefined exception raised by the runtime system. User-defined exception can be raised (thrown) by user code. Exception handlers specify remedial actions or proper shutdown Exceptions can be stored and re-raised later

concurrency - 2 Predefined exceptions in Ada Defined in Standard: Constraint_Error : value out of range Program_Error : illegality not detectable at compile-time: unelaborated package, exception during finalization... Storage_Error : allocation cannot be satisfied (heap or stack) Tasking _Error : communication failure Defined in Ada.IO_Exceptions: Data_Error, End_Error, Name_Error, Use_Error, Mode_Error, Status_Error, Device_Error

concurrency - 3 Handling exceptions Any begin-end block can have an exception handler: procedure test is x : integer := 25; y : integer := 0; begin x := x / y; exception when Constraint_Error => Put_Line (“as expected”); when others => Put_Line (“out of the blue!”); end;

concurrency - 4 A common idiom with Integer_Text_Io; use Integer_Text_Io; function Get_Data return Integer is X : Integer; begin loop -- as long as input is not legal begin Get (X); return X; -- if got here, input is valid exception when others => Put_Line (“input must be integer, try again”); end; end loop; end;

concurrency - 5 Exception propagation When an exception is raised, the current sequence of statements is abandoned If an exception handler for the current exception is present, it is executed, and the current frame is completed Otherwise, the frame is discarded, and the enclosing dynamic scopes are examined to find a frame that contains a handler for the current exception If none is found, the program terminates The current frame is never resumed

concurrency - 6 User-defined Exceptions Client-server contract: if inputs are proper, either the output is correct or else client is notified of failure. The inputs are the responsibility of the client (the caller). package Stacks is Stack_Empty : exception; … package body Stacks is procedure Pop (X : out Integer; From : in out Stack) is begin if Empty (From) then raise Stack_Empty; else...

concurrency - 7 The scope of exceptions Exception has the same visibility as other declared entities: to handle an exception it must be visible in the handler An others clause can handle unamable exceptions partially when others => Put_Line (“disaster somewhere”); raise; -- propagate exception, program will terminate

concurrency - 8 Exception information An exception is not a type: we cannot declare exception variables and assign to them An exception occurrence is a value that can be stored and examined an exception occurrence may include additional information: source location of occurrence, contents of stack, etc. Predefined package Ada.Exceptions contains needed machinery.

concurrency - 9 Ada.Exceptions package Ada.Exceptions is type Exception_Id is private; type Exception_Occurrence is limited private; function Exception_Identity (X : Exception_Occurrence) return Exception_Id; function Exception_Name (X : Exception_Occurrence) return String; procedure Save_Occurrence (Target : out Exception_Occurrence; Source : Exception_Occurrence); procedure Raise_Exception (E : Exception_Id; Message : in String := “”)...

concurrency - 10 Using exception information exception when Expected : Constraint_Error => Save_Occurrence (Event_Log, Expected); when Trouble : others => Put_Line (“unexpected “ & Exception_Name (Trouble) & “ raised”); Put_Line (“shutting down”); raise;...

concurrency - 11 Exceptions in C++ Same runtime model Exceptions are classes Handlers appear in try blocks try { some_complex_calculation (); } catch (range_error) { // range error might be raised // in some_complex_calculation cerr << “oops\n”; catch (zero_divide) { // ditto for zero_divide cerr << “why is x zero?\n”; }

concurrency - 12 Defining and throwing exceptions The program throws an object. There is nothing in the declaration to indicate it will be used as an exception. struct Zero_Divide { public: int lineno; // useful information Zero_Divide () {…} // constructor … try { … if (x == 0) throw Zero_Divide (..); // call constructor and go

concurrency - 13 Exceptions and inheritance A handler names a class, and can handle an object of a derived class as well: class Matherr {}; // a bare object, no info class Overflow: public Matherr {…}; class Underflow: public Matherr {…}; class Zero_Divide: public Matherr {…}; try { weather_prediction_model (…); // who knows what will happen } catch (Overflow) {… // e.g. change parameters in caller catch (Matherr) { … // Underflow, Zero_Divide handled here catch (…); // handle anything else (ellipsis)

concurrency - 14 Exceptions in Java Model and terminology similar to C++: exception are objects that are thrown and caught try blocks have handlers, which are examined in succession a handler for an exception can handle any object of a derived class Differences: all exceptions are extension of predefined class Throwable checked exceptions are part of method declaration the finally clause specifies clean-up actions

concurrency - 15 If a method might throw an exception, callers should know about it public void replace (String name, Object newvalue) throws NoSuch { Attribute attr := find (name); if (attr == null) throw new NoSuch (name); // build before throw newvalue.update (attr); } Caller must have a handler for NoSuch, or else must be declared as throwing NoSuch itself. Compiler checks. Only required for checked exceptions (not predefined ones, which are extensions of RuntimeException and Error).

concurrency - 16 Mandatory cleanup actions Some cleanups must be performed whether the method terminates normally or throws an exception. public void encrypt (String file) throws StreamException { Stream input; try { input = new Stream (file); iterator Words = new iterator (input); for (word w = Words.init (); Words.more(); w = Words.next()) { RSAencode(w); // may fail somewhere } finally { if (input != null) input.close(); }; //regardless of how we exit

concurrency - 17 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional communication Non-determinism

concurrency - 18 Concurrent programming Synchronous and asynchronous models of communication Description of simultaneous, independent activities A task is an independent thread of control, with own stack, program counter and local environment. Ada Tasks communicate through Rendez-vous protected objects Shared variables Java threads communicate through shared objects (preferably synchronized)

concurrency - 19 Task Declarations A task type is a limited type task type worker; -- declaration; public interface type Worker_Id is access worker; -- a conventional access type task body worker is -- actions performed in lifetime begin loop -- forever. Will be shutdown from compute; -- the outside. end loop; end worker;

concurrency - 20 Task Declarations A task type can be a component of a composite. The number of tasks in a program is not fixed at compile-time. W1, W2 : Worker; -- two individual tasks type Crew is array (Integer range <>) of worker; First_Shift : Crew (1.. 10); -- a group of tasks type Monitored is record Counter : Integer; Agent : Worker; end record;

concurrency - 21 Task Activation When does a task start running: If statically allocated, at the next begin If dynamically allocated, at the point of allocation. declare W1, W2 : Worker; Joe : Worker_Id := new Worker; -- Starts working at once Third_Shift : Crew (1..N); -- some number of them begin -- activate W1, W2, and the … -- third_shift end; -- wait for them (not Joe) -- to complete

concurrency - 22 Task Services A task can perform some actions on request from another task The interface (declaration) of the task specifies the available actions (entries) A task can also execute some actions on its own behalf, without external requests or communication. task type Device is entry Read (X : out Integer); entry Write (X : Integer); end Device;

concurrency - 23 Synchronization: Rendez-vous Caller makes explicit request: entry call Callee (server) states its availability: accept statement If server is not available, caller blocks and queues up on the entry for later service If both present and ready, parameters are transmitted to server. Server performs action Out parameters are transmitted to caller Caller and server continue execution independently

concurrency - 24 Example : semaphore Simple mechanism to create critical sections: section of code that must be executed by only one task at a time task type semaphore is entry P; -- Dijkstra’s terminology entry V; -- from the Dutch end semaphore; task body semaphore is begin loop accept P; -- won’t accept another P until a caller asks for V accept V; end loop; end semaphore;

concurrency - 25 Using a semaphore A task that needs exclusive access to the critical section executes: Sema.P; -- critical section code Sema.V; If in the meantime another task calls Sema.P, it blocks, because the semaphore does not accept a call to P until after the next call to V: the other task is blocked until the current one releases by makin an entry call to V. programming hazards: someone else may call V : race condition no one calls V: other callers are deadlocked.

concurrency - 26 Delays and Time A delay statement can be executed anywhere at any time, to make current task quiescent for a stated interval: delay 0.2; -- type is Duration, units of seconds We can also specify that the task stop until a certain specified time: delay until Noon; -- defined elsewhere

concurrency - 27 Time package Ada.Calendar is type Time is private; -- nanoseconds since epoch, maybe subtype Year_Number is Integer range ;.. function Clock return Time; -- some operating system service procedure Split (Year : out Year_Number; Month : out Month_Number; Day : out Day_Number; Seconds : out Day_Duration; function “+” (Left : Time; Right : Duration) return Time; … end;

concurrency - 28 Conditional Communication Need to protect against excessive delays, deadlock, starvation, caused by missing or malfunctioning tasks. Timed entry call: caller waits for rendez-vous a stated amount of time: select Disk.Write (value => 12, Track => 123); -- Disk is a task or delay 0.2; end select; If Disk does not accept within 0.2 Secs, go do something else.

concurrency - 29 Conditional Communication (ii) Conditional entry call: caller ready for rendez-vous only if no one else is queued, and rendez-vous can begin at once: select Disk.Write (value => 12, Track => 123); else Put_Line (“device busy”); end select; Print message if call cannot be accepted immediately.

concurrency - 30 Conditional communication (iii) The server may accept a call only if the internal state of the task is appropriate: select when not full => accept Write (Val : Integer); or when not empty => Accept Read (Var : out Integer); or delay 0.2; -- maybe something will happen end select; If several guards are open and callers are present, any one of the calls may be accepted : non-determinism.

concurrency - 31 Concurrency in Java Two primitive notions class thread interface runnable An object of class thread is mapped into an operating system primitive interface runnable { public void run ( ); }; Any class can become a thread of control, by supplying a run method

concurrency - 32 Threads at work class PingPong extends Thread { String word; int delay; PingPong (String whatToSay, int delayTime) { word = whatToSay; } public void run () { try { for (;;) { // infinite loop System.out.print (word + “ “); sleep (delay); // yield processor } } catch (InterruptedException e) { return; // terminate thread } } }

concurrency - 33 Activation and execution public static void man (String[] args) { new PingPong (“ping”, 33).start ( ); // activate new PingPong (“pong”, 100).start ( ); // activate } Call to start activates thread, which executes run method Threads can communicate through shared objects Classes can have synchronized methods to enforce critical sections.