Practice Session 9 Exchanger CyclicBarrier Exceptions.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
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.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Exception Handling. Definition  The term exception is shorthand for the phrase "exceptional event.“  An exception is an event, which occurs during the.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Slides Credit Umair Javed LUMS Web Application Development.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Java Exceptions a quick review….
Exceptions Networking
Exceptions In this lecture:
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Handling Exceptions.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Web Design & Development Lecture 7
CSE 143 Java Exceptions 1/18/2019.
Exceptions handling Try, catch blocks Throwing exceptions.
Java Exceptions Dan Fleck CS211.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Practice Session 9 Exchanger CyclicBarrier Exceptions

java.util.concurrent.Exchanger A combination of a barrier with data passing between threads. Allows a pair of threads to wait for each other at a rendezvous point. Allows exchange of data between the two threads at that point. Notes: – Two threads must be paired together for this to work. – The two threads must exchange data at the rendezvous point. How is exchanging data done? – Using exchange() method.

java.util.concurrent.Exchanger How is exchanging data done? – Thread A reaches rendezvous point, and executes the exchange() method: If thread B is already waiting, the data is passed. If thread B is not waiting, thread A waits for thread B: – For unlimited time: exchange(V x) – With a specified timeout: exchange(V x, long timeout, TimeUnit unit) » x: the object to be exchanged. » timeout: the number of TimeUnit to wait. » unit: java.util.concurrent.TimeUnit MICROSECONDS MILLISECONDS NANOSECONDS SECONDS API: Code Example: Exchanger

java.util.concurrent.CyclicBarrier A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized group of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released. API:

Creating a CyclicBarrier – CyclicBarrier barrier = new CyclicBarrier(2); //specify how many threads are to wait at it, before releasing them. – CyclicBarrier barrier = new CyclicBarrier(2, barrierAction); //barrierAction is a Runnable that is executed once the last thread arrives.

Waiting at a CyclicBarrier: – barrier.await(); – barrier.await(10,TimeUnit.Seconds); The waiting thread waits at the barrier until either: – The last thread arrives (calls await()) – The thread is interrupted by another thread – Another waiting thread is interrupted – Another waiting thread times out while waiting at the barrier. – The CyclicBarrier reset() methods is called by some external thread.

Example Sum all values in a matrix IntHolder – a synchronized class to hold the sum of the matrix elements; updated by 2 threads summing matrix rows. MeetingPointAction – creates a meeting point, and 2 threads to work on 2 consecutive rows. The barrier action is a new MeetingPointAction

Advanced Synchronization Methods Semaphore: a lock with N permits; N threads may acquire a key at the same time. A thread can acquire more than one Permit using: acquire( ). CountDownLatch: Allows one or more threads to wait until other threads complete; Used for initialization/finalization purposes. Exchanger: Allows a pair of threads to wait for each other at a rendezvous point, and exchange data. CyclicBarrier: same as Exchanger but for any number of fixed threads; can be reused.

Exceptions

Java uses exceptions to handle errors and other exceptional events. Examples: Reading a file that does not exist or is inaccessible. Dividing a number by zero. Network is down, URL does not exist. Accessing an array element at a certain index that is not within the bounds of the array.

Code Example public class ExceptionExample { public static void main(String[] args) { int[] a = {2, 4, 6, 8}; for(int j = 0; j <= a.length ; j++) System.out.println(a[j]); } /* output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at spl.examples.exceptions.ExceptionExample.main(ExceptionExample.java:7) */

What Is an Exception? An exception is an event that occurs during the execution of a program disrupting the normal flow of instructions. When an error occurs within a method: – the method creates an object and hands it off to the runtime system. – The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. Call Stack: – The ordered list of methods that had been called to get to the method where the error occurred. – This is the set of possible "somethings" to handle the exception.

The runtime system searches the call stack for a method that contains a block of code that can handle the exception, exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. If no handler is found, the exception is thrown to the JVM, which terminates the program, and prints the exception together with its call stack to the console.

Exception Types There are 2 different types of exceptions: Unchecked Exceptions: – Errors: External to the application The application usually cannot anticipate or recover from them. They are indicated by Error and its subclasses. Example: OutOfMemoryError - the application ran out of memoryOutOfMemoryError

– Runtime Exceptions: Internal to the application The application usually cannot anticipate or recover from. Usually indicate programming bugs, such as logic errors or improper use of an API. Runtime exceptions are those indicated by RuntimeException and its subclasses. Examples: – NullPointerException - the application is trying to access a null pointer (an uninitialized object). NullPointerException – ArrayIndexOutOfBoundsException - the application is trying to access an array outside of its boundaries. ArrayIndexOutOfBoundsException

Checked Exceptions: – Exceptional conditions that a well-written application should anticipate and recover from. – Inherited from the core Java class Exception.Exception – Checked exceptions must be handled in your code (catch it), or passed to the calling code for handling (declare that your method might throw it using the throws keyword at the method signature). – Example: FileNotFoundException - the application is trying to access a file that does not exist.FileNotFoundException

Exception Hierarchy

Throwing an Exception public class Clock { private int fHours, fMinutes, fSeconds; // constructors and methods //There is no need to catch IllegalArgumentException or to declare that the function throws it //since it's a RuntimeException (unchecked exception). public void setTime(int hours, int minutes, int seconds){ if (hours 12 || minutes 59 || seconds 59) throw new(IllegalArgumentException(“Invalid time”); //this code does not run if an exception occurs. fHours = hours; fMinutes = minutes; fSeconds = seconds; }

Creating New Exceptions Create a new exception by extending Exception, or one of its subclasses.Exception //a class that uses our new exception public class Stack { int elements[]; int top; //next empty location in the elements array //... constructor, push(), isEmpty() //There is no need to declare StackUnderflowException a s thrown in the method signature //since it's a RuntimeException (unchecked exception) public int pop() { if (isEmpty()) throw new StackUnderflowException(); return elements[--top]; } //StackUnderflowException inherits all of its parent's methods and does not add any of its own //You can also add methods to StackUnderflowExcep tion or override existing methods to change //printing format, for example public class StackUnderflowException extends Runti meException {}

Catching Exceptions A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Each catch block is an exception handler and handles the type of exception indicated by its argument, which must inherits from the Throwable class.Throwable

import java.io.*; public class FirstLine { public static void main(String[] args){ String name = args[0]; try{ BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readLine(); System.out.println(line); //handle FileNotFoundException }catch (FileNotFoundException e) { System.out.println("File not found: "+ name); //handle IOException }catch (IOException e) { System.out.println("Problem: " + e); }

Handling Exceptions When handling exceptions you should restore stable state and do one of the following: – Change conditions and retry. – Clean up and fail (re-throw exception) If an exception extends another exception and you would like to handle each separately, then the catch block that handles the sub exception should be before the catch block that handles the base exception.

Exceptions don't have to be handled in the method in which they occurred. You can let a method further up the call stack handle the exception. This is done by adding a throws clause to the method declaration. public BufferedReader openFileForReading(String filename) throws IOException{ return new BufferedReader(new FileReader(filename)); }

The Finally Block Comes right after all catch blocks in a try-catch clause. The code found in the finally block is always executed before exiting the try/catch block, even if an exception occurred, or a return/continue/break statement were encountered. It is usually used for cleanup code, since it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. For more information regarding exceptions see: Oracle Exceptions Tutorial.Oracle Exceptions Tutorial

import java.io.*; public class FirstLine { public static void main(String[] args){ String name = args[0]; try{ BufferedReader file = new BufferedReader(new FileR eader(name)); String line = file.readLine(); System.out.println(line); //handle FileNotFoundException }catch (FileNotFoundException e) { System.out.println("File not found: "+ name); //handle IOException }catch (IOException e) { System.out.println("Problem: " + e); }finally{ if (file != null) { System.out.println("Closing the file:" + na me); file.close(); } else { System.out.println("Unable to open file:" + name); }