ICE1341 Programming Languages Spring 2005 Lecture #20 & 21 Lecture #20 & 21 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications.

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Shared-Memory Model and Threads Intel Software College Introduction to Parallel Programming – Part 2.
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.
4 Control Statements: Part 1.
Module 6: Process Synchronization
Process Description and Control
1 Concurrency: Deadlock and Starvation Chapter 6.
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Distributed Systems Architectures
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Chapter 5 Input/Output 5.1 Principles of I/O hardware
Exception Handling and Event Handling
Turing Machines.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
Chapter 24 Lists, Stacks, and Queues
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Names, Bindings, Type Checking, and Scopes
Procedures. 2 Procedure Definition A procedure is a mechanism for abstracting a group of related operations into a single operation that can be used repeatedly.
Chapter 3: Processes.
1 Processes and Threads Chapter Processes 2.2 Threads 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
Types of selection structures
Chapter 15 Multithreading, Networks, and Client/Server Programming
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Chapter 8 Improving the User Interface
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
ICE1341 Programming Languages Spring 2005 Lecture #16 Lecture #16 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
ICE1341 Programming Languages Spring 2005 Lecture #13 Lecture #13 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University.
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.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
ISBN Chapter 14 Exception Handling and Event Handling.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11 Exception Handling and Event Handling.
ISBN Chapter 13 Concurrency. Copyright © 2006 Addison-Wesley. All rights reserved.2 Chapter 13 Topics Introduction Introduction to Subprogram-Level.
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
May 6, ICE 1341 – Programming Languages (Lecture #19) In-Young Ko Programming Languages (ICE 1341) Lecture #19 Programming Languages (ICE 1341)
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
May 21, ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
1 Chapter 13 © 2002 by Addison Wesley Longman, Inc Introduction - Concurrency can occur at four levels: 1. Machine instruction level 2. High-level.
Concurrency (Based on:Concepts of Programming Languages, 8th edition, by Robert W. Sebesta, 2007)
(12.1) COEN Concurrency and Exceptions  Coroutines  Physical and logical concurrency  Synchronization – semaphores – monitors – message passing.
Chapter 13 Concurrency. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Introduction Concurrency can occur at four levels: –Machine instruction.
CPS 506 Comparative Programming Languages
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 12 Concurrency can occur at four levels: 1. Machine instruction level 2. High-level language.
Lecture 13 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
ISBN Chapter 14 Exception Handling and Event Handling.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
ICS 313: Programming Language Theory Chapter 14: Exceptions.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Chapter 13 Concurrency. Corrected and improved by Assoc. Prof. Zeki Bayram, EMU, North Cyprus. Original Copyright © 2012 Addison-Wesley. All rights reserved1-2.
Java Exceptions a quick review….
Exception Handling and Event Handling
Exception Handling and Event Handling
Exception Handling and Event Handling
Chapter 13 Concurrency.
Lecture 12 Concepts of Programming Languages
Subject : T0152 – Programming Language Concept
Chapter 13 Concurrency.
Exception Handling and Event Handling
Presentation transcript:

ICE1341 Programming Languages Spring 2005 Lecture #20 & 21 Lecture #20 & 21 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University (ICU)

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Announcements Project Presentation Sessions (May 26 th ) Project Presentation Sessions (May 26 th ) 7 minutes for each team (in English) 7 minutes for each team (in English) Explain design goals of your team Explain design goals of your team Show a sample program (XML and Target languages) Show a sample program (XML and Target languages) Discussions Discussions Language design decisions that made it easy and efficient to implement the cross compiler Language design decisions that made it easy and efficient to implement the cross compiler Language design decisions that made it difficult to implement the cross compiler Language design decisions that made it difficult to implement the cross compiler Please send me (iko.AT. icu.ac.kr) your presentation file (PPT files) by noon on May 26 th Please send me (iko.AT. icu.ac.kr) your presentation file (PPT files) by noon on May 26 th

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Announcements Final Exam: Final Exam: Dater & Time: Monday May 30, :00PM-6:00PM Dater & Time: Monday May 30, :00PM-6:00PM Allowed to bring a hand-written ‘cheat sheet’ (A4 size, double-sided) Allowed to bring a hand-written ‘cheat sheet’ (A4 size, double-sided) Covering: Covering: Chapter 7 – 11 Chapter 7 – 11 Chapter 12 except 12.7, 12.8 and 12.9 Chapter 12 except 12.7, 12.8 and 12.9 Chapter 13 except 13.7 Chapter 13 except 13.7 Chapter 14 Chapter 14

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Object-oriented Programming Languages Object-oriented Programming Languages Software Reuse Software Reuse Overriden Methods Overriden Methods Abstract Classes and Methods Abstract Classes and Methods Design Issues for OOPLs Design Issues for OOPLs Exclusive use of objects in typing systems Exclusive use of objects in typing systems Subclsses as subtypes Subclsses as subtypes Polymorphism and dynamic type checking Polymorphism and dynamic type checking Multiple inheritance Multiple inheritance Object allocation and deallocation mechanisms Object allocation and deallocation mechanisms Object-oriented Processing of XML Data Object-oriented Processing of XML Data Last Lecture

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University This Lecture Concurrency Concurrency Categories of Concurrency Categories of Concurrency Semaphores Semaphores Exception Handling Exception Handling Exception Handling in Java Exception Handling in Java Exception Handling in Ada Exception Handling in Ada Event Handling in Java Event Handling in Java

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Chapter 13 Concurrency

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Concurrency “A program is said to be concurrent if it contains more than one active execution context” [M. Scott] “A program is said to be concurrent if it contains more than one active execution context” [M. Scott] void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { while (true) { while (true) { try { System.out.print("A"); sleep(0,1); try { System.out.print("A"); sleep(0,1); } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { while (true) { while (true) { try { System.out.print("B"); sleep(0,1); try { System.out.print("B"); sleep(0,1); } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();} Java Forking two concurrent execution threads Main Program Control Printing “A” Printing “B”

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Categories of Concurrency Thread of control: A sequence of program points reached as control flows through the program Thread of control: A sequence of program points reached as control flows through the program Categories of Concurrency: Categories of Concurrency: Physical concurrency: Concurrency supported multiple independent processors Physical concurrency: Concurrency supported multiple independent processors Logical concurrency: Concurrency presented by time-sharing one processor (software can be designed as if there were multiple threads of control) Logical concurrency: Concurrency presented by time-sharing one processor (software can be designed as if there were multiple threads of control) Coroutines provide only quasi-concurrency Coroutines provide only quasi-concurrency * AW Lecture Notes

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Subprogram-Level Concurrency (1) Task (Process): A program unit that can be in concurrent execution with other program units Task (Process): A program unit that can be in concurrent execution with other program units  Tasks differ from ordinary subprograms in that:  A task may be implicitly started  When a program unit starts the execution of a task, the program is not necessarily suspended  When a task’s execution is completed, control may not return to the caller void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { while (true) { while (true) { try { System.out.print("A"); try { System.out.print("A"); } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { while (true) { while (true) { try { System.out.print("B"); try { System.out.print("B"); } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();}

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Subprogram-Level Concurrency (2) A task is disjoint if it does not communicate with or affect the execution of any other task in the program in any way A task is disjoint if it does not communicate with or affect the execution of any other task in the program in any way Task communication is necessary for synchronization Task communication is necessary for synchronization Shared nonlocal variables Shared nonlocal variables Parameters Parameters Message passing Message passing Race Condition: a situation in which more than one tasks are racing to use shared resources Race Condition: a situation in which more than one tasks are racing to use shared resources int count = 0; void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { try { while (count++ < 20) { try { while (count++ < 20) { System.out.print("A"); System.out.print("A"); sleep(0, 1); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (count++ < 20) { try { while (count++ < 20) { System.out.print("B"); System.out.print("B"); sleep(0, 1); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();}

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Subprogram-Level Concurrency Race Condition: a situation in which more than one tasks are racing to use shared resources Race Condition: a situation in which more than one tasks are racing to use shared resources int count = 0; void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { try { while (count++ < 20) { try { while (count++ < 20) { System.out.print("A"); System.out.print("A"); sleep(0, 1); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (count++ < 20) { try { while (count++ < 20) { System.out.print("B"); System.out.print("B"); sleep(0, 1); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();} A BAB count < 20  T count++ count = 19 count = 21 count < 20  T count++ print one more character

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Semaphores – Dijkstra 1965 class Semaphore { int s = 0; int s = 0; public synchronized void p() { public synchronized void p() { while (s < 0) continue; while (s < 0) continue; s--; s--; } public synchronized void v() { public synchronized void v() { s++; s++; }} int count = 0; Semaphore sem = new Semaphore(); void concurrentPrint() { (new Thread () { public void run() { (new Thread () { public void run() { try { while (true) { try { while (true) { sem.p(); // wait sem.p(); // wait if (count++ < 20) if (count++ < 20) { System.out.print("A"); sleep(0, 1); } sem.v(); // release sem.v(); // release } } catch (Exception e) { } } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { public void run() { (new Thread () { public void run() { try {while (true) { try {while (true) { sem.p(); // wait sem.p(); // wait if (count++ < 20) if (count++ < 20) { System.out.print(“B"); sleep(0, 1); } sem.v(); // release sem.v(); // release } } catch (Exception e) { } } } catch (Exception e) { } } }).start(); }).start();} Semaphore: a data structure consisting of a counter and a queue for storing task descriptors Guarded code Guarded code

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Synchronization Problems Cooperation Synchronization: synchronization in counting something Cooperation Synchronization: synchronization in counting something e.g., The previous example of sharing a counter, Sharing a buffer by a producer and a consumer Competition Synchronization: synchronization in sharing a resource Competition Synchronization: synchronization in sharing a resource e.g., Dining Philosophers problem Peterson & Silberschatz

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Dining Philosophers Problem Peterson & Silberschatz Five philosophers spend their lives thinking and eating Five philosophers spend their lives thinking and eating The philosophers share a circular table The philosophers share a circular table In the center of the table, there is a bowl of rice In the center of the table, there is a bowl of rice The table is laid with five chopsticks The table is laid with five chopsticks When a philosopher gets hungry, he tries to pickup two chopsticks that are closest to him When a philosopher gets hungry, he tries to pickup two chopsticks that are closest to him Dijstra 1965

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Solving The Dining Philosophers Problem Using Semaphores Peterson & Silberschatz Semaphore[] chopsticks = new Semaphore[5]; chopsticks = new Semaphore[5]; chopsticks[0] = new Semaphore(); … while (true) { chopsticks[i].p(); chopsticks[i].p(); chopsticks[(i+1) % 5].p(); chopsticks[(i+1) % 5].p();… // eat … chopsticks[i].v(); chopsticks[i].v(); chopsticks[(i+1) % 5].v(); chopsticks[(i+1) % 5].v();… // think …}

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Evaluation of Semaphores Misuse of semaphores (when a P operation is left out) can cause failures in cooperation synchronization Misuse of semaphores (when a P operation is left out) can cause failures in cooperation synchronization e.g., out of index, buffer overflow Misuse of semaphores (when a V operation is left out) can cause failures in competition synchronization Misuse of semaphores (when a V operation is left out) can cause failures in competition synchronization e.g., infinite loop, deadlock

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Synchronized Objects int count = 0; Object s = new Object(); void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { try { while (true) { try { while (true) { synchronized(s) { synchronized(s) { if (count++ >= 20) break; } System.out.print("A"); sleep(0, 1); System.out.print("A"); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (true) { try { while (true) { synchronized(s) { synchronized(s) { if (count++ >= 20) break; } System.out.print("B"); sleep(0, 1); System.out.print("B"); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();} Java Only the thread that owns the semaphore object can execute the guarded code

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Monitors public class PrintAB { int count = 0; int count = 0; public synchronized boolean printA() { public synchronized boolean printA() { if (count++ < 20) { if (count++ < 20) {System.out.print(“A”); return true; } return false; return false; } public synchronized boolean printB() { public synchronized boolean printB() { if (count++ < 20) { if (count++ < 20) {System.out.print(“B”); return true; } return false; return false; }}… void concurrentPrint() { final PrintAB prtJob = new PrintAB(); final PrintAB prtJob = new PrintAB(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (prtJob.printA()) try { while (prtJob.printA()) sleep(0, 1); sleep(0, 1); } catch(Exception e) { … } } catch(Exception e) { … } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (prtJob.printB()) try { while (prtJob.printB()) sleep(0, 1); sleep(0, 1); } catch(Exception e) { … } } catch(Exception e) { … } } }).start(); }).start();}

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Monitors – Hoare 1974 Encapsulation of shared data structures for semaphores with their operations and hide their representations Encapsulation of shared data structures for semaphores with their operations and hide their representations Access to the shared data in the monitor is limited to a single process at a time Access to the shared data in the monitor is limited to a single process at a time Multiple calls are queued Multiple calls are queued e.g., Concurrent Pascal, Modula, Mesa, Java (objects can be used as monitors) e.g., Concurrent Pascal, Modula, Mesa, Java (objects can be used as monitors) public class PrintAB { int count = 0; int count = 0; public synchronized boolean printA() { public synchronized boolean printA() { if (count++ < 20) { if (count++ < 20) {System.out.print(“A”); return true; } return false; return false; } public synchronized boolean printB() { public synchronized boolean printB() { if (count++ < 20) { if (count++ < 20) {System.out.print(“B”); return true; } return false; return false; }}

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University A Monitor Example Cooperation synchronization using a monitor Cooperation synchronization using a monitor Shared bounded buffer (queue) problem Shared bounded buffer (queue) problem

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University A Monitor Example public class BoundedBuffer { int size = 100; int size = 100; int[] buf = new int[size]; int[] buf = new int[size]; int front = 0, rear = 0, count = 0; int front = 0, rear = 0, count = 0; public synchronized void insert(int data) { public synchronized void insert(int data) { throws InterruptedException { throws InterruptedException { if (count == size) wait(); if (count == size) wait(); buf[rear] = data; buf[rear] = data; rear = (rear + 1) % size; count++; rear = (rear + 1) % size; count++; if (count == 1) notify(); if (count == 1) notify(); } public synchronized int remove() { public synchronized int remove() { throws InterruptedException{ throws InterruptedException{ if (count == 0) wait(); if (count == 0) wait(); int result = buf[front]; int result = buf[front]; front = (front+1) % size; count--; front = (front+1) % size; count--; if (count == size-1) notify(); if (count == size-1) notify(); return result; return result; }} Producer threads call ‘insert’ to add data Producer threads call ‘insert’ to add data Consumer threads call ‘remove’ to fetch data Consumer threads call ‘remove’ to fetch data Causes the current thread to wait until another thread invokes ‘notify’ Wakes up a thread that is waiting on this object’s monitor

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Evaluation of Monitors Support for competition synchronization is great Support for competition synchronization is great Support for cooperation synchronization is very similar as with semaphores, so it has the same problems Support for cooperation synchronization is very similar as with semaphores, so it has the same problems

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Message Passing A message Tasks are distributed across different programs and/or different machines

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Message Passing Models A way to handle the problem of synchronizing program units in a distributed system A way to handle the problem of synchronizing program units in a distributed system Synchronous Message Passing Model: A task is blocked until its counterpart accepts a message Synchronous Message Passing Model: A task is blocked until its counterpart accepts a message Rendezvous: A message transmission when a sender task’s message is accepted by a receiver task Rendezvous: A message transmission when a sender task’s message is accepted by a receiver task Asynchronous Message Passing Model: A task proceeds its execution after sending a message to its counterpart Asynchronous Message Passing Model: A task proceeds its execution after sending a message to its counterpart A sender must know the entry name of the receiver, but not vice versa (asymmetric) A sender must know the entry name of the receiver, but not vice versa (asymmetric)

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University A Message Passing Example … try { ServerSocket s = new ServerSocket(80); ServerSocket s = new ServerSocket(80); while (true) { while (true) { Socket incoming = s.accept(); Socket incoming = s.accept(); InputStream in = incoming.getInputStream(); InputStream in = incoming.getInputStream(); createThreadToProcessCommand(in); createThreadToProcessCommand(in); …. …. } } catch (Exception e) { … } … try { Socket s = new Socket(“ 80); Socket s = new Socket(“ 80); OutputStream out = s.getOutputStream(); OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); InputStream in = s.getInputStream(); createThreadToSendCommand(out); createThreadToSendCommand(out); createThreadToReceiveResults(in); createThreadToReceiveResults(in); … } catch (Exception e) { … } Rendezvous HTTP Server (Web Server) HTTP Client Entry Name

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Rendezvous Time Lines

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Java Threads Java threads are lightweight tasks – all threads run in the same address space Java threads are lightweight tasks – all threads run in the same address space c.f., Ada tasks are heavyweight threads (processes) that run in their own address spaces c.f., Ada tasks are heavyweight threads (processes) that run in their own address spaces class MyThread extends Thread { public void run() { public void run() { … // Task body // Task body … }}… Thread aTask = new MyThread(); aTask.start(); … aTask.setPriority (Thread.MAX_PRIORITY); (Thread.MAX_PRIORITY);… aTask.join(); … Controls the thread scheduler Waits for the thread to complete

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Statement-Level Concurrency High-Performance Fortran (HPF) High-Performance Fortran (HPF) The compiler maps a program onto a multiprocessor architecture The compiler maps a program onto a multiprocessor architecturee.g., REAL list_1(1000), list_2(1000) INTEGER list_3(500), list_4(501) !HPF$ PROCESSORS proc (10) !HPF$ DISTRIBUTE (BLOCK) ONTO procs :: list_1, list_2 !HPF$ ALIGN list_1(index) WITH list_4 (index+1) … list_1 (index) = list_2(index) list_1 (index) = list_2(index) list_3(index) = list_4(index+1) list_3(index) = list_4(index+1) … FORALL (index = 1:1000) list_1(index) = list_2(index) * 1.2 list_1(index) = list_2(index) * 1.2

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Chapter 14 Exception Handling and Event

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling Exception: An unexpected condition that is raised (thrown) during program execution Exception: An unexpected condition that is raised (thrown) during program execution Hardware Detectable Exceptions: e.g., Floating-point overflow, I/O errors Hardware Detectable Exceptions: e.g., Floating-point overflow, I/O errors Software Detectable Exceptions: e.g., Array subscript range errors, null pointer exceptions Software Detectable Exceptions: e.g., Array subscript range errors, null pointer exceptions Exception Handling: The special processing that may be required after detection of an exception is called Exception Handling: The special processing that may be required after detection of an exception is called Exception Handler: The exception handling code unit Exception Handler: The exception handling code unit OPEN (UNIT=10, FILE='data.txt', STATUS='OLD') OPEN (UNIT=10, FILE='data.txt', STATUS='OLD') 30 READ(10, *, END=40, ERR=50) NUM … GOTO 30 GOTO 30 FORTRAN

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling Example void fileCopy(String file1, String file2) { try { try { FileInputStream in = FileInputStream in = new FileInputStream(file1); new FileInputStream(file1); FileOutputStream out = FileOutputStream out = new FileOutputStream(file2); new FileOutputStream(file2); int data; int data; while ((data = in.read()) >= 0) while ((data = in.read()) >= 0) out.write(data); out.write(data); } catch (FileNotFoundException e1) { } catch (FileNotFoundException e1) { System.err.println System.err.println (“Cannot open input or output file.”); (“Cannot open input or output file.”); } catch (IOException e2) { } catch (IOException e2) { System.err.println System.err.println (“Cannot read or write data.”); (“Cannot read or write data.”); }} May throw the File Not Found Exception May throw the IO Exception Exception Handlers Java

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Descriptions in the Java API Manual

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling Control Flow Main Program Control Exception Exception Handler Continuation of the main program Catching the exception Main Program Control Exception Operating System Discontinuation of the main program Uncaught exception

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Advantages of Built-in Exception Handling Programmers do not need to explicitly define, detect, and raise exceptions Programmers do not need to explicitly define, detect, and raise exceptions Exception propagation allows a high level of reuse of exception handling code Exception propagation allows a high level of reuse of exception handling code * AW Lecture Notes

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exceptions in Java All exceptions are objects of classes that are descendants of the Throwable class All exceptions are objects of classes that are descendants of the Throwable class Serious problems that a user program should not try to catch e.g., Heap overflow MyIOException (User-defined Exception) Error … Exception IOException … FileNotFoundException… RunTimeException Unchecked Exceptions User programs are not required to handle themUser programs are not required to handle them The compiler do not concern themThe compiler do not concern them Checked Exceptions Program errors e.g., Array index out-of-bound, Null pointer exception

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling in Java Exceptions cannot be disabled Exceptions cannot be disabled Binding Exceptions to Handlers – An exception is bound to the first handler with a parameter is the same class as the thrown object or an ancestor of it Binding Exceptions to Handlers – An exception is bound to the first handler with a parameter is the same class as the thrown object or an ancestor of it Specify code that is to be executed, regardless of what happens in the try construct Specify code that is to be executed, regardless of what happens in the try construct void fileCopy(String file1, String file2) { try { try { FileInputStream in = FileInputStream in = new FileInputStream(file1); new FileInputStream(file1); FileOutputStream out = FileOutputStream out = new FileOutputStream(file2); new FileOutputStream(file2); int data; int data; while ((data = in.read()) >= 0) while ((data = in.read()) >= 0) out.write(data); out.write(data); } catch (FileNotFoundException e1) { } catch (FileNotFoundException e1) { System.err.println(“Can’t open a file.”); System.err.println(“Can’t open a file.”); } catch (IOException e2) { } catch (IOException e2) { System.err.println(“Can’t read or write.”); System.err.println(“Can’t read or write.”); } finally { } finally { in.close(); in.close(); out.close(); out.close(); }}

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Propagation in Java A method can be declared to propagate certain exceptions to its caller by using ‘throws’ A method can be declared to propagate certain exceptions to its caller by using ‘throws’ Exceptions are dynamically bound to handlers Exceptions are dynamically bound to handlers To insure that all exceptions are caught, a handler can be defined to have an Exception class parameter To insure that all exceptions are caught, a handler can be defined to have an Exception class parameter There are built-in operations in exception objects There are built-in operations in exception objects void fileCopy(String file1, String file2) throws FileNotFoundException, throws FileNotFoundException, IOException { IOException { FileInputStream in = FileInputStream in = new FileInputStream(file1); new FileInputStream(file1); FileOutputStream out = FileOutputStream out = new FileOutputStream(file2); new FileOutputStream(file2); int data; int data; while ((data = in.read()) >= 0) while ((data = in.read()) >= 0) out.write(data); out.write(data); in.close(); out.close(); in.close(); out.close();} void myMain() { try { try { fileCopy (“source.txt”, “dest.txt”); fileCopy (“source.txt”, “dest.txt”); } catch (Exception e) { } catch (Exception e) { e.printStackTrace(); e.printStackTrace(); }}

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Stack Trace in Java Java’s exception stack trace shows the dynamic chain of exception propagations Java’s exception stack trace shows the dynamic chain of exception propagations java.io.FileNotFoundException: source.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream. (Unknown Source) at ExceptionTest.fileCopy(ExceptionTest.java:9) at ExceptionTest.myMain(ExceptionTest.java:20) at ExceptionTest.main(ExceptionTest.java:30)

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University User-defined Exceptions in Java User-defined exceptions can be thrown by throw User-defined exceptions can be thrown by throw Rethrowing (reraising) an exception Rethrowing (reraising) an exception void fileCopy(String file1, String file2) throws MyIOException { throws MyIOException { try { try { FileInputStream in = FileInputStream in = new FileInputStream(file1); new FileInputStream(file1); FileOutputStream out = FileOutputStream out = new FileOutputStream(file2); new FileOutputStream(file2); int data; int data; while ((data = in.read()) >= 0) while ((data = in.read()) >= 0) out.write(data); out.write(data); in.close(); out.close(); in.close(); out.close(); } catch (Exception e) { } catch (Exception e) { throw new MyIOException(); throw new MyIOException(); }}

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling in Ada (1) Exception handlers are bound for program blocks: Exception handlers are bound for program blocks:begine -- block body -- block body exception exception when exception_name { | exception_name } => statement_sequence when exception_name { | exception_name } => statement_sequence when... when... [when others => statement_sequence] [when others => statement_sequence]end; User-defined Exceptions: User-defined Exceptions: exception_name_list : exception; raise [exception_name] Exception conditions can be disabled with (‘pragma’ is a directive to the compiler): Exception conditions can be disabled with (‘pragma’ is a directive to the compiler): pragma SUPPRESS(exception_list)

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling in Ada (2) Predefined Exceptions: Predefined Exceptions: CONSTRAINT_ERROR - index constraints, range constraints, etc. CONSTRAINT_ERROR - index constraints, range constraints, etc. NUMERIC_ERROR - numeric operation cannot return a correct value (overflow, division by zero, etc.) NUMERIC_ERROR - numeric operation cannot return a correct value (overflow, division by zero, etc.) PROGRAM_ERROR - call to a subprogram whose body has not been elaborated PROGRAM_ERROR - call to a subprogram whose body has not been elaborated STORAGE_ERROR - system runs out of heap STORAGE_ERROR - system runs out of heap TASKING_ERROR - an error associated with tasks TASKING_ERROR - an error associated with tasks * AW Lecture Notes

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling in C++ Exceptions are bound to handlers through the type of the parameter: Exceptions are bound to handlers through the type of the parameter: int new_grade; int new_grade; try { if (index 9) try { if (index 9) throw (new_grade); … throw (new_grade); … } catch (int grade) { } catch (int grade) { if (grade == 100) … if (grade == 100) … } All exceptions are user-defined All exceptions are user-defined A throw without an operand can only appear in a handler; when it appears, it simply reraises the exception, which is then handled elsewhere A throw without an operand can only appear in a handler; when it appears, it simply reraises the exception, which is then handled elsewhere

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Event Handling in Java An event is created by an external action such as a user interaction through a GUI An event is created by an external action such as a user interaction through a GUI The event handler is a segment of code that is called in response to an event The event handler is a segment of code that is called in response to an event JButton helloButton = new JButton(“Hello”); JButton helloButton = new JButton(“Hello”); helloButton.addActionListener(new AbstractAction() { helloButton.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) { System.out.println(“Hello World!”); System.out.println(“Hello World!”); } } A JButton Event Listeners Button Pressed Event

Spring ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exercises for the Final Exam Problems in the text book Problems in the text book Chapter 7 – Problem Set #13 Chapter 7 – Problem Set #13 Chapter 8 – Review Questions #5, 8 Chapter 8 – Review Questions #5, 8 Chapter 9 – Problem Set #5 Chapter 9 – Problem Set #5 Chapter 10 – Problem Set #2 Chapter 10 – Problem Set #2 Chapter 11 – Problem Set #3 Chapter 11 – Problem Set #3 Chapter 12 – Problem Set #1, 2 Chapter 12 – Problem Set #1, 2 Chapter 13 – Problem Set #6, 9 (Explain the reason or prove it by writing a sample Java program) Chapter 13 – Problem Set #6, 9 (Explain the reason or prove it by writing a sample Java program)