• No results found

B.tech CS S8 Principles of Programming Languages Notes Module 5

N/A
N/A
Protected

Academic year: 2021

Share "B.tech CS S8 Principles of Programming Languages Notes Module 5"

Copied!
19
0
0

Loading.... (view fulltext now)

Full text

(1)

MODULE-5

MODULE-5

ADVANCES IN LANGUAGE DESIGN ADVANCES IN LANGUAGE DESIGN

Advances in Language design - Variations of subprogram control, Parallel programming, Advances in Language design - Variations of subprogram control, Parallel programming, Introduction to exception handling - Exception handling in JAVA, Hardware developments, Introduction to exception handling - Exception handling in JAVA, Hardware developments, software architecture

software architecture

SUBPROGRAM CONTROL SUBPROGRAM CONTROL Subprogram control:

Subprogram control:interaction among subprograms and how subprograms manage to passinteraction among subprograms and how subprograms manage to pass data among themselves in a structured and efficient manner.

data among themselves in a structured and efficient manner.

Terminology: Terminology: Function call

Function call– subprograms that return values directly– subprograms that return values directly Subroutine callSubroutine call– subprograms that– subprograms that operate only through side effects on shared data.

operate only through side effects on shared data. A.

A. SUBPROGRAM SEQUENCE CONTROLSUBPROGRAM SEQUENCE CONTROL Simple subprogram call return

Simple subprogram call return

Copy rule view of subprograms: the effect of a call statement is the same as if the subprogram Copy rule view of subprograms: the effect of a call statement is the same as if the subprogram were copied and inserted into the main program.

were copied and inserted into the main program. Implicit assumptions present in this view :

Implicit assumptions present in this view : o Subprograms cannot be recursive

o Subprograms cannot be recursive o Explicit call statements are required o Explicit call statements are required

o Subprograms must execute completely at each call o Subprograms must execute completely at each call o Immediate transfer of control at point

o Immediate transfer of control at point of callof call o Single execution sequence

o Single execution sequence

Simple call-return subprograms Simple call-return subprograms

Execution of subprograms Outline of the method: Execution of subprograms Outline of the method:

1. Subprogram definition and subprogram activation. 1. Subprogram definition and subprogram activation. The definition is translated into a template, used to

The definition is translated into a template, used tocreate an activationcreate an activation each time a subprogrameach time a subprogram is called.

is called.

2. Subprogram activation: consists of  2. Subprogram activation: consists of 



a code segment (the invariant part) - executable code and constantsa code segment (the invariant part) - executable code and constants



an activation record (the dynamic part) - local an activation record (the dynamic part) - local data, parametersdata, parameters

created anew each time the subprogram is called, destroyed when the subprogram returns. created anew each time the subprogram is called, destroyed when the subprogram returns. Execution is implemented by the use of two system-defined pointers:

Execution is implemented by the use of two system-defined pointers:



Current-instruction pointerCurrent-instruction pointer– CIP-address of the next statement to be executed– CIP-address of the next statement to be executed



Current-environment pointerCurrent-environment pointer– CEP- pointer to the activation record.– CEP- pointer to the activation record. On

On callcallinstruction:instruction:

c. An activation record is created. c. An activation record is created.

d. Current CIP and CEP are saved in the created activation record as

d. Current CIP and CEP are saved in the created activation record asreturn point return point 

e. CEP is assigned the address of the activation record. e. CEP is assigned the address of the activation record.

f. CIP gets the address of the first instruction in the code segment f. CIP gets the address of the first instruction in the code segment

(2)

g. The execution continues from the address in CIP g. The execution continues from the address in CIP On

On returnreturn

h. The old values of CIP and CEP are retrieved . h. The old values of CIP and CEP are retrieved . i. The execution continues from the address in CIP i. The execution continues from the address in CIP

Restrictions

Restrictionsof the model:of the model: at most one activationat most one activation of any subprogramof any subprogram

The simplest implementation:

The simplest implementation:to allocate storage for each activation as an extension of the codeto allocate storage for each activation as an extension of the code segment. Used in FORTRAN and COBOL. The activation record is not destroyed - only

segment. Used in FORTRAN and COBOL. The activation record is not destroyed - only reinitialized for each subprogram execution.

reinitialized for each subprogram execution.

Hardware support - CIP is the program counter, CEP is not used, simple jump executed on Hardware support - CIP is the program counter, CEP is not used, simple jump executed on return.

return.

Stackbased implementation

-Stack-based implementation -the simplest run-time storage management techniquethe simplest run-time storage management technique call statements : push CIP and CEP return statements : pop CIP and CEP off of the stack. call statements : push CIP and CEP return statements : pop CIP and CEP off of the stack. Used in most C implementations LISP: uses the stack as an environment.

Used in most C implementations LISP: uses the stack as an environment.

RECURSIVE SUBPROGRAMS RECURSIVE SUBPROGRAMS Specification

Specification

Syntactically - no difference Semantically - multiple activations o

Syntactically - no difference Semantically - multiple activations o f the same subprogram existf the same subprogram exist simultaneously at some point in the execution.

simultaneously at some point in the execution.

Implementation Implementation

Stack-based - CIP and CEP are stored in stack, forming a dynamic chain of links. Stack-based - CIP and CEP are stored in stack, forming a dynamic chain of links.



A new activation record is created for each call and destroyed at return.A new activation record is created for each call and destroyed at return. 

The lifetimes of the activation records cannot overlap - they are nested.The lifetimes of the activation records cannot overlap - they are nested.

Some language compilers (C, Pascal) always assume recursive structure of subprograms, Some language compilers (C, Pascal) always assume recursive structure of subprograms, while in others non-recursive subprograms are implemented in the simple way.

while in others non-recursive subprograms are implemented in the simple way.

VARIATIONS OF SUBPROGRAM CONTROL VARIATIONS OF SUBPROGRAM CONTROL

The simple call-return subprogram activation was based on several assumptions: The simple call-return subprogram activation was based on several assumptions: 1. No recursive subprograms

1. No recursive subprograms 2. Explicit call statements 2. Explicit call statements

3. Subprograms must execute completely at each call 3. Subprograms must execute completely at each call 4. Control must be transferred immediately at the

4. Control must be transferred immediately at the point of callpoint of call 5. There must be a single execution sequence

5. There must be a single execution sequence

Changing these assumptions will result in different processing models. Changing these assumptions will result in different processing models. Here we shall discuss assumptions 2 through 5.

Here we shall discuss assumptions 2 through 5.

Assumption Assumption

Removing the assumption results in Removing the assumption results in

Explicit call statements Explicit call statements Exception handlers Exception handlers

Subprograms must execute completely at each call Subprograms must execute completely at each call Co-routines

Co-routines

Control must be transferred immediately at the point

Control must be transferred immediately at the point of callof call Scheduled subprograms

Scheduled subprograms

There must be a single execution sequence There must be a single execution sequence

(3)

1. Exceptions and exception handlers 1. Exceptions and exception handlers

Exception Handlers are subprograms used to handle some special situations, called exceptions. Exception Handlers are subprograms used to handle some special situations, called exceptions. They are

They arenot invoked by explicit calls.not invoked by explicit calls. Instead they are invoked when a particular condition orInstead they are invoked when a particular condition or event occurs, e.g.

event occurs, e.g.

Error conditions Unpredictable conditions Tracing and monitoring Error conditions Unpredictable conditions Tracing and monitoring Exception handlers typically contain only:

Exception handlers typically contain only: o A set of declarations of local variables and o A set of declarations of local variables and o A sequence of executable statements

o A sequence of executable statements Exception Handlers can be

Exception Handlers can be o predefined in the language o predefined in the language o programmer defined

o programmer defined

Raising

Raising andandcatchingcatchingan exceptionan exception

Languages provide methods for raising (throwing) and testing for exceptions. Languages provide methods for raising (throwing) and testing for exceptions.

Example: Example: try try {{ statement1; statement2; … statement1; statement2; … if 

if badConditionbadCondition throwthrow ExceptionName; }ExceptionName; }

catch

catch ExceptionName { ……….// do something for exception…….}ExceptionName { ……….// do something for exception…….} Here

Here try, throwtry, throw andandcatchcatch are keywords, different language may have different keywords.are keywords, different language may have different keywords.

Implementation Implementation

e. Operating system exceptions - raised directly by hardware interrupts. e. Operating system exceptions - raised directly by hardware interrupts. f. Programmer defined - the translator inserts code to handle the exceptions. f. Programmer defined - the translator inserts code to handle the exceptions.

co-routines co-routines Co-routines

Co-routines: subprograms that can return con: subprograms that can return control to the caller before completion of execution.trol to the caller before completion of execution.

Implementation:

Implementation: similar to the simple call-return structure, the difference is similar to the simple call-return structure, the difference is in handling thein handling the CIP. Each co-routine has IP location in its activation record, used to provide the value for CIP on CIP. Each co-routine has IP location in its activation record, used to provide the value for CIP on resuming the execution.

resuming the execution.

scheduled subprograms scheduled subprograms

Subprogram scheduling results from relaxation of the assumption that execution of a subprogram Subprogram scheduling results from relaxation of the assumption that execution of a subprogram should always be initiated immediately on its call.

should always be initiated immediately on its call.

Subprograms scheduling techniques Subprograms scheduling techniques::

o Execution after other subprograms – call B after A o Execution after other subprograms – call B after A

o Execution when a Boolean expression becomes true – call B when X=5 o Execution when a Boolean expression becomes true – call B when X=5 o Execution on the basis of a simulated time scale – call B when time=25 o Execution on the basis of a simulated time scale – call B when time=25 o Execution based on

o Execution based on priority – call B with priority 7priority – call B with priority 7

Implementation: Implementation:

Scheduling is a run-time activity. The process is controlled (usually) by a system-defined Scheduling is a run-time activity. The process is controlled (usually) by a system-defined scheduler program that maintains a list of currently scheduled subprogram activations. scheduler program that maintains a list of currently scheduled subprogram activations.

(4)

PARALLEL PROGRAMMING PARALLEL PROGRAMMING Parallel processing

Parallel processing: the execution of more than one program/subprogram simultaneously. A: the execution of more than one program/subprogram simultaneously. A subprogram that can execute concurrently with other subprograms is called a

subprogram that can execute concurrently with other subprograms is called atasktask or aor aprocess.process.

Two basic ways to achieve parallel processing: Two basic ways to achieve parallel processing: a. hardware supported:

a. hardware supported: a multiprocessor system a d

a multiprocessor system a distributed (parallel) computer systemistributed (parallel) computer system b. software simulated

b. software simulated

separate tasks run concurrently on the virtual computer, one task at a time on the actual computer separate tasks run concurrently on the virtual computer, one task at a time on the actual computer - time sharing.

- time sharing.

1. PRINCIPLES OF PARALLEL

1. PRINCIPLES OF PARALLEL PROGRAMMING LANGUAGESPROGRAMMING LANGUAGES Issues to be addressed:

Issues to be addressed:

o

oVariable definitionsVariable definitions mutable

mutable : values may be assigned to the variables and changed during program execution (as in: values may be assigned to the variables and changed during program execution (as in sequential languages).

sequential languages).

definitional

definitional: variable may be assigned a value only once.: variable may be assigned a value only once. o

oParallel compositionParallel composition: A parallel statement, which causes additional: A parallel statement, which causes additionalthreads of controlthreads of controltoto begin executing.

begin executing. o

o Execution models (Program structureExecution models (Program structure))

Transformational

Transformational: transforms the input data into an appropriate output value. E.G. parallel: transforms the input data into an appropriate output value. E.G. parallel matrix multiplication

matrix multiplication

Reactive

Reactive: the program reacts to external stimuli called: the program reacts to external stimuli called eventsevents. E.G. real-time control systems.. E.G. real-time control systems. Non-determinism - the behavior depends on the occurring events.

Non-determinism - the behavior depends on the occurring events. o

o CommunicationCommunication shared memory

shared memorywith common data objects accessed by each parallel program;with common data objects accessed by each parallel program;

messages. messages.

o

o SynchronizationSynchronization. Parallel programs must be able to coordinate the execution of various. Parallel programs must be able to coordinate the execution of various threads of control. threads of control. 2. CONCURRENT EXECUTION 2. CONCURRENT EXECUTION a. Programming constructs a. Programming constructs 

using parallel execution primitives of the operating system (C can invoke the fork operationusing parallel execution primitives of the operating system (C can invoke the fork operation of Unix )

of Unix )



Using parallel constructs.Using parallel constructs.

A programming language parallel construct indicates parallel execution A programming language parallel construct indicates parallel execution

Example:

Example:AND statement (programming language level)AND statement (programming language level) Syntax: statement1

Syntax: statement1andandstatement2statement2and …and …statementNstatementN Semantics: All statements execute in parallel.

Semantics: All statements execute in parallel.

call

call ReadProcessReadProcessand calland callWrite processWrite processand calland callExecuteUserProgram ;ExecuteUserProgram ;

No assumption is made on the order of execution, i.e. the tasks can be executed in a while loop No assumption is made on the order of execution, i.e. the tasks can be executed in a while loop

b. Guarded commands b. Guarded commands



Guard: a condition that can be true or false.Guard: a condition that can be true or false.



Guards are associated with statements.Guards are associated with statements.



A statement is executed when its guard becomes true.A statement is executed when its guard becomes true.

Non-determinism of execution - the guards acquire their truth value in run-time. Non-determinism of execution - the guards acquire their truth value in run-time.

(5)

Guarded if  Guarded if ::

if 

if B1 ® S1 | B2 ® S2 | … Bn ® SnB1 ® S1 | B2 ® S2 | … Bn ® Sn fifi

If some guards Bi are true one of the corresponding statements is executed. If some guards Bi are true one of the corresponding statements is executed.

Guarded repetition statement Guarded repetition statement do

do B1 ® S1 | B2 ® S2 | … Bn ® SnB1 ® S1 | B2 ® S2 | … Bn ® Snodod

If some guards Bi are true one of the corresponding statements is executed. The process repeats If some guards Bi are true one of the corresponding statements is executed. The process repeats while there are true guards.

while there are true guards.

c. Tasks c. Tasks



Tasks are subprograms that run in parallel with the program that has initiated them.Tasks are subprograms that run in parallel with the program that has initiated them.



They are dependents on the initiating program.They are dependents on the initiating program.



The initiating program cannot terminate until all of its dependents terminate.The initiating program cannot terminate until all of its dependents terminate. 

A task may have multiple simultaneous activations.A task may have multiple simultaneous activations.

Task activation Task activation

Explicit call statements Implicitly, based on their declaration. Explicit call statements Implicitly, based on their declaration.

Types of interaction

Types of interaction(with respect to the degree of awareness of the existence of other(with respect to the degree of awareness of the existence of other tasks/processes)

tasks/processes)



Tasks unaware of each otherTasks unaware of each other

Independent tasks that are not intended to work together. Independent tasks that are not intended to work together.



Tasks indirectly aware of each otherTasks indirectly aware of each other

Tasks share access to some object, such as an I/O buffer, but are not necessarily aware of each Tasks share access to some object, such as an I/O buffer, but are not necessarily aware of each other by their respective IDs.

other by their respective IDs.



Tasks directly aware of each otherTasks directly aware of each other

Tasks that are designed to work jointly on some activity and are able to communicate with each Tasks that are designed to work jointly on some activity and are able to communicate with each other. The communication provides a way to synchronize, or coordinate, the various activities. other. The communication provides a way to synchronize, or coordinate, the various activities. Typically, communication can be characterized as consisting of messages of some sort.

Typically, communication can be characterized as consisting of messages of some sort.

Control Problems Control Problems



Mutual exclusionMutual exclusion

Two tasks require access to a single non-shareable resource Two tasks require access to a single non-shareable resource.. Critical resource

Critical resource- the resource in question.- the resource in question.Critical sectionCritical section in the program - the portion in in the program - the portion in thethe program that uses the resource

program that uses the resourceThe ruleThe rule: only one program at a time can be allowed in its critical: only one program at a time can be allowed in its critical section

section



DeadlockDeadlock

Involves at least two processes Involves at least two processes

P1 waits for an event to be produced by P2 P2 waits for an event to be produced by P1 P1 waits for an event to be produced by P2 P2 waits for an event to be produced by P1



StarvationStarvation

Involves at least three processes P1, P2, P3 competing for non-shareable resource. P1 and P2 Involves at least three processes P1, P2, P3 competing for non-shareable resource. P1 and P2 alternatively use the resource, P3 may indefinitely be denied access to that resource.

alternatively use the resource, P3 may indefinitely be denied access to that resource.

Synchronization of Tasks Synchronization of Tasks

If several tasks work on one problem and share a resource, they may need to be synchronized at If several tasks work on one problem and share a resource, they may need to be synchronized at certain points of their execution.

certain points of their execution.

Techniques for synchronization: Techniques for synchronization: Interrupts

-Interrupts -provided by the operating systemprovided by the operating system.. Semaphores

-Semaphores -shared data objects, with two primitive operations - signal and wait.shared data objects, with two primitive operations - signal and wait.

Messages

Messages - information is sent from one task to another. The sending task may continue to- information is sent from one task to another. The sending task may continue to execute.

(6)

Guarded commands

-Guarded commands -force synchronization by insuring conditions are met before the tasks areforce synchronization by insuring conditions are met before the tasks are executed.

executed.

Rendezvous

-Rendezvous -similar to messages, the sending task waits for an answer.similar to messages, the sending task waits for an answer.

Example: Semaphores Example: Semaphores The setting:

The setting:



Special variable called a semaphore is used for signalingSpecial variable called a semaphore is used for signaling



If a process is waiting for a signal, it is suspended until that signal is sentIf a process is waiting for a signal, it is suspended until that signal is sent



Wait and signal operations cannot be interruptedWait and signal operations cannot be interrupted



Queue is used to hold processes waiting on the semaphoreQueue is used to hold processes waiting on the semaphore Semaphore is a variable that has an

Semaphore is a variable that has aninteger valueinteger value



May beMay beinitialized to a nonnegative numberinitialized to a nonnegative number



WaitWaitoperationoperationdecrementsdecrementsthe semaphore valuethe semaphore value



SignalSignaloperationoperation incrementsincrementssemaphore valuesemaphore value

Mutual exclusion with semaphores Mutual exclusion with semaphores

Each task performs: Each task performs: wait(s); wait(s);  /* critical section */   /* critical section */  signal(s); signal(s);

The produces/consumer problem The produces/consumer problem



One or more producers are generating data and placing these in a bufferOne or more producers are generating data and placing these in a buffer



A single consumer is taking items out of the buffer one at timeA single consumer is taking items out of the buffer one at time



Only one producer or consumer may access the buffer at any one timeOnly one producer or consumer may access the buffer at any one time

Solution : Solution :

ss- semaphore for entering the critical section- semaphore for entering the critical section delaydelay - semaphore to ensure reading from non-- semaphore to ensure reading from non-empty buffer empty buffer Producer: Consumer: Producer: Consumer: produce(); wait(delay); produce(); wait(delay); wait (s); wait(s); wait (s); wait(s); append(); take(); append(); take(); signal(delay); signal(s); signal(delay); signal(s); signal(s); consume(); signal(s); consume(); 3. Persistent systems 3. Persistent systems Traditional software: Traditional software:

Data stored outside of program - persistent data Data processed in main memory - transient data Data stored outside of program - persistent data Data processed in main memory - transient data Processing model:

Processing model:

Read data from file Process data Store results on file Read data from file Process data Store results on file

Consider an application system where several programs running in parallel use and update a Consider an application system where several programs running in parallel use and update a large database, e.g. ticket reservation system. The traditional processing model is inefficient. large database, e.g. ticket reservation system. The traditional processing model is inefficient.

Solution1:

Solution1: keep the database in main memory as a shared data object. Drawbacks: in case of keep the database in main memory as a shared data object. Drawbacks: in case of  system failure all data will be lost.

system failure all data will be lost.

Solution2:

Solution2: keep the database in main memory as a shared data object and maintain its image onkeep the database in main memory as a shared data object and maintain its image on a file system - recording each change at the time it occurs

a file system - recording each change at the time it occurs

Languages that do not make distinction between persistent and transient data, and automatically Languages that do not make distinction between persistent and transient data, and automatically reflect changes in the database, are called

reflect changes in the database, are calledpersistent languagespersistent languages Design issues:

Design issues:

0. A mechanism to indicate an object is persistent 0. A mechanism to indicate an object is persistent

(7)

Approach: assume all data are transient and indicate which objects are persistent Approach: assume all data are transient and indicate which objects are persistent 1. A mechanism to address a persistent object

1. A mechanism to address a persistent object

The language can develop its own model of persistent storage The language can develop its own model of persistent storage 2. Simultaneous access to an individual persistent object 2. Simultaneous access to an individual persistent object Use of semaphores

Use of semaphores

3. Check type compatibility of persistent objects 3. Check type compatibility of persistent objects

Because of the multiple programs that access persistent data, name equivalence is difficult to use, Because of the multiple programs that access persistent data, name equivalence is difficult to use, structural equivalence is the preferred method in persistent languages.

structural equivalence is the preferred method in persistent languages.

4. Client-server computing 4. Client-server computing 4.1. Network models

4.1. Network models

o

o Centralized,Centralized,where a single processor does the scheduling and informs the other machines aswhere a single processor does the scheduling and informs the other machines as to the tasks to execute. When completed, the assigned processor will indicate that it is ready to to the tasks to execute. When completed, the assigned processor will indicate that it is ready to do another task 

do another task  o

o Distributed or peer-to-peer,Distributed or peer-to-peer,where each machine is an equal and the process of scheduling iswhere each machine is an equal and the process of scheduling is spread among all of the machines.

spread among all of the machines.

- One processor broadcasts a message to all the processors, and an inactive processor could - One processor broadcasts a message to all the processors, and an inactive processor could respond with the message "I'll do it."

respond with the message "I'll do it."

- Alternatively, each machine in the network will individually invoke a task on a specified - Alternatively, each machine in the network will individually invoke a task on a specified machine elsewhere in the network. In this way, work gradually gets propagated around the machine elsewhere in the network. In this way, work gradually gets propagated around the network.

network.

4.2. Client-server mediator architecture 4.2. Client-server mediator architecture Client machine:

Client machine:

o Interacts with user o Interacts with user

o Has protocol to communicate with server o Has protocol to communicate with server

Server: Server:

o Decides where data is located o Decides where data is located o Accesses data

o Accesses data

o Mediator is software that uses encoded knowledge about sets of data to create information for a o Mediator is software that uses encoded knowledge about sets of data to create information for a higher class of application.

higher class of application.

o Issues: May be communicating with multiple clients simultaneously o Issues: May be communicating with multiple clients simultaneously



Need to keep each such transaction separateNeed to keep each such transaction separate



Multiple local address spaces in serverMultiple local address spaces in server

EXCEPTIONS AND EXCEPTION HANDLERS EXCEPTIONS AND EXCEPTION HANDLERS

Exception Handlers are subprograms used to handle some special situations, called exceptions. Exception Handlers are subprograms used to handle some special situations, called exceptions. They are

They arenot invoked by explicit calls.not invoked by explicit calls.

Instead they are invoked when a particular condition or event occurs, e.g. Instead they are invoked when a particular condition or event occurs, e.g. Error conditions

Error conditions

Unpredictable conditions Unpredictable conditions Tracing and monitoring Tracing and monitoring

Exception handlers typically contain only: Exception handlers typically contain only:

(8)

• A sequence of executable statementsA sequence of executable statements

Exception Handlers can be Exception Handlers can be

• predefined in the languagepredefined in the language •

• programmer definedprogrammer defined

Raising

Raising andandcatchingcatchingan exceptionan exception

Languages provide methods for raising (throwing) and testing for exceptions. Languages provide methods for raising (throwing) and testing for exceptions.

Example: Example: try try {{ statement1; statement1; statement2; statement2; … … if 

if badConditionbadCondition throwthrow ExceptionName;ExceptionName; }}

catch

catch ExceptionNameExceptionName

{ ……….// do something for exception…….} { ……….// do something for exception…….} Here

Here try, throwtry, throw andandcatchcatch are keywords, different language may have different keywords.are keywords, different language may have different keywords.

Implementation Implementation

a.

a. Operating system exceptions - raised directly by hardware interrupts.Operating system exceptions - raised directly by hardware interrupts. b.

b. Programmer defined - the translator inserts code to handle the exceptions.Programmer defined - the translator inserts code to handle the exceptions.

CO-ROUTINES CO-ROUTINES Co-routines

(9)

Implementation:

Implementation: similar to the simple call-return structure, the difference is similar to the simple call-return structure, the difference is in handling thein handling the CIP.

CIP.

Each co-routine has IP location in its activation record, used to provide the value for CIP Each co-routine has IP location in its activation record, used to provide the value for CIP on resuming the execution.

on resuming the execution.

SCHEDULED SUBPROGRAMS SCHEDULED SUBPROGRAMS

Subprogram scheduling results from relaxation of the assumption that execution of  Subprogram scheduling results from relaxation of the assumption that execution of  a subprogram should always be initiated immediately on its call.

a subprogram should always be initiated immediately on its call.

Subprograms scheduling techniques Subprograms scheduling techniques::

o

o Execution after other subprograms – call Execution after other subprograms – call B after AB after A o

o Execution when a Boolean expression becomes true – call B whenExecution when a Boolean expression becomes true – call B when

X=5 X=5

o

o Execution on the basis of a simulated time scale – call B whenExecution on the basis of a simulated time scale – call B when

time=25 time=25

o

o Execution based on prioritExecution based on priority – call B with priority 7y – call B with priority 7

Implementation: Implementation:

Scheduling is a run-time activity. The process is controlled (usually) by a system-defined Scheduling is a run-time activity. The process is controlled (usually) by a system-defined scheduler program that maintains a list of currently scheduled subprogram activations. scheduler program that maintains a list of currently scheduled subprogram activations. A

A parallel programming modelparallel programming modelis a concept that enables the expression of parallel programsis a concept that enables the expression of parallel programs which can be compiled and executed. The value of a programming model is usually judged on its which can be compiled and executed. The value of a programming model is usually judged on its generality: how well a range of different problems can be expressed and how well they execute generality: how well a range of different problems can be expressed and how well they execute on a range of different architectures. The implementation of a programming model can take on a range of different architectures. The implementation of a programming model can take several forms such as libraries invoked from traditional sequential languages, language several forms such as libraries invoked from traditional sequential languages, language extensions, or complete new execution models.

(10)

Consensus on a particular programming model is important as it enables software expressed Consensus on a particular programming model is important as it enables software expressed within it to be transportable between different architectures. The von Neumann model has within it to be transportable between different architectures. The von Neumann model has facilitated this with sequential architectures as it provides

facilitated this with sequential architectures as it provides an efficientan efficientbridgebridgebetween hardwarebetween hardware and software, meaning that high-level languages can be efficiently compiled to it and it can be and software, meaning that high-level languages can be efficiently compiled to it and it can be efficiently implemented in hardware.

efficiently implemented in hardware.

JAVA - EXCEPTIONS HANDLING JAVA - EXCEPTIONS HANDLING AN EXCEPTION IS A PROBLEM

AN EXCEPTION IS A PROBLEMthat arises during the execution of a program. Anthat arises during the execution of a program. An exception can occur for many different reasons, including the following:

exception can occur for many different reasons, including the following:

• A user has entered invalid data.A user has entered invalid data. •

• A file that needs to be opened cannot be found.A file that needs to be opened cannot be found. •

• A network connection has been lost in the middle of communications, or the JVM has runA network connection has been lost in the middle of communications, or the JVM has run

out of memory. out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

physical resources that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three To understand how exception handling works in Java, you need to understand the three categories of exceptions:

categories of exceptions:

• Checked exceptions:Checked exceptions:A checked exception is an exception that is typically a user error orA checked exception is an exception that is typically a user error or

a problem that cannot be foreseen by the programmer. For example, if a file is to be a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the

simply be ignored at the time of compilation.time of compilation.

• Runtime exceptions:Runtime exceptions: A runtime exception is an exception that occurs that probablyA runtime exception is an exception that occurs that probably

could have been avoided by the programmer. As opposed to checked exceptions, runtime could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

exceptions are ignored at the time of compliation.

• Errors:Errors: These are not exceptions at all, but problems that arise beyond the control of theThese are not exceptions at all, but problems that arise beyond the control of the

user or the programmer. Errors are typically ignored in your code because you can rarely user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

They are also ignored at the time of compilation.

Exception Hierarchy: Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class. The exception class is a All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

Error which is derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime

indicate errors generated by the runtime environment. Example : JVM is environment. Example : JVM is out of Memory.out of Memory. Normally programs cannot recover from errors.

(11)

The Exception class has two main subclasses : IOException class and RuntimeException Class. The Exception class has two main subclasses : IOException class and RuntimeException Class.

Here is a list of most common checked and unchecked

Here is a list of most common checked and unchecked Java's Built-in ExceptionsJava's Built-in Exceptions..

Exceptions Methods: Exceptions Methods:

Following is the list of important medthods available in the Throwable class. Following is the list of important medthods available in the Throwable class.

SN

SN Methods Methods with with DescriptionDescription

1 1

public String getMessage() public String getMessage()

Returns a detailed message about the exception that has occurred. This message is Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.

initialized in the Throwable constructor.

2

2 public Throwable getCause()public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object. Returns the cause of the exception as represented by a Throwable object.

3

3 public String toString()public String toString()

Returns the name of the class concatenated with the result of getMessage() Returns the name of the class concatenated with the result of getMessage()

4 4

public void printStackTrace() public void printStackTrace()

Prints the result of toString() along with the stack

Prints the result of toString() along with the stack trace to System.err, the error outputtrace to System.err, the error output stream.

(12)

5 5

public StackTraceElement [] getStackTrace() public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0 Returns an array containing each element on the stack trace. The element at index 0

represents the top of the call stack, and the last element in the array represents the method at represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

the bottom of the call stack.

6 6

public Throwable fillInStackTrace() public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

previous information in the stack trace.

Catching Exceptions: Catching Exceptions:

A method catches an exception using a combination of the

A method catches an exception using a combination of thetrytry andandcatchcatch keywords. A try/catchkeywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block  block is placed around the code that might generate an exception. Code within a try/catch block  is referred to as protected code, and the syntax for using try/catch looks like the following:

is referred to as protected code, and the syntax for using try/catch looks like the following: try try {{  //Protected code  //Protected code }catch(ExceptionName e1) }catch(ExceptionName e1) {{  //Catch block   //Catch block  }}

A catch statement involves declaring the type of exception you are trying to catch. If an A catch statement involves declaring the type of exception you are trying to catch. If an

exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If  exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If  the type of exception that occurred is listed in a catch block, the exception is passed to the catch the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

block much as an argument is passed into a method parameter.

Example: Example:

The following is an array is declared with 2 elements. Then the code tries to access the 3rd The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

element of the array which throws an exception.  // File Name : ExcepTest.java

 // File Name : ExcepTest.java import java.io.*;

import java.io.*;

public class ExcepTest{ public class ExcepTest{

public static void main(String args[]){ public static void main(String args[]){

try{ try{

int a[] = new int[2]; int a[] = new int[2];

(13)

System.out.println("Access element three :" + a[3]); System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){

}catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception

System.out.println("Exception thrown thrown :" + :" + e);e); }}

System.out.println("Out of the block"); System.out.println("Out of the block"); }}

}}

This would produce following result: This would produce following result: Exception

Exception thrown thrown :java.lang.ArrayIndexOutOfBoundsException: :java.lang.ArrayIndexOutOfBoundsException: 33 Out of the block 

Out of the block 

Multiple catch Blocks: Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

like the following: try try {{  //Protected code  //Protected code }catch(ExceptionType1 e1) }catch(ExceptionType1 e1) {{  //Catch block   //Catch block  }catch(ExceptionType2 e2) }catch(ExceptionType2 e2) {{  //Catch block   //Catch block  }catch(ExceptionType3 e3) }catch(ExceptionType3 e3) {{  //Catch block   //Catch block  }}

The previous statements demonstrate three catch blocks, but you can have any number of them The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. stops execution and the exception is thrown down to the previous method on the call stack.

Example: Example:

Here is code segment showing how to use multiple try/catch statements. Here is code segment showing how to use multiple try/catch statements.

(14)

try try {{

file = new FileInputStream(fileName); file = new FileInputStream(fileName); x = (byte) file.read(); x = (byte) file.read(); }catch(IOException i) }catch(IOException i) {{ i.printStackTrace(); i.printStackTrace(); return -1; return -1;

}catch(FileNotFoundException f) //Not valid! }catch(FileNotFoundException f) //Not valid! {{ f.printStackTrace(); f.printStackTrace(); return -1; return -1; }}

The throws/throw Keywords: The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the

If a method does not handle a checked exception, the method must declare it using thethrowsthrows

keyword. The throws keyword appears at the end of a method's signature. keyword. The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the

by using thethrowthrow keyword. Try to understand the different in throws and throw keywords.keyword. Try to understand the different in throws and throw keywords. The following method declares that it throws a RemoteException:

The following method declares that it throws a RemoteException: import java.io.*;

import java.io.*;

public class className public class className {{

public void deposit(double amount) throws RemoteException public void deposit(double amount) throws RemoteException {{

 // Method implementation  // Method implementation

throw new RemoteException(); throw new RemoteException(); }}

 //Remainder of class definition  //Remainder of class definition }}

Amethod can declare that it throws more than one exception, in which case the exceptions are Amethod can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:

throws a RemoteException and an InsufficientFundsException: import java.io.*;

import java.io.*;

public class className public class className

(15)

{{

public void withdraw(double amount) throws RemoteException, public void withdraw(double amount) throws RemoteException,

InsufficientFundsException InsufficientFundsException {{  // Method implementation  // Method implementation }}

 //Remainder of class definition  //Remainder of class definition }}

The finally Keyword The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally block of  The finally keyword is used to create a block of code that follows a try block. A finally block of  code always executes, whether or not an exception has occurred.

code always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax: A finally block appears at the end of the catch blocks and has the following syntax: try try {{  //Protected code  //Protected code }catch(ExceptionType1 e1) }catch(ExceptionType1 e1) {{  //Catch block   //Catch block  }catch(ExceptionType2 e2) }catch(ExceptionType2 e2) {{  //Catch block   //Catch block  }catch(ExceptionType3 e3) }catch(ExceptionType3 e3) {{  //Catch block   //Catch block  }finally }finally {{

 //The finally block always executes.  //The finally block always executes. }}

Example: Example:

public class ExcepTest{ public class ExcepTest{

public static void main(String args[]){ public static void main(String args[]){

int a[] = new int[2]; int a[] = new int[2];

(16)

try{ try{

System.out.println("Access element three :" + a[3]); System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){

}catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception

System.out.println("Exception thrown thrown :" + :" + e);e); }}

finally{ finally{

a[0] = 6; a[0] = 6;

System.out.println("First element value: " +a[0]); System.out.println("First element value: " +a[0]);

System.out.println("The finally statement is executed"); System.out.println("The finally statement is executed"); }}

}} }}

This would produce following result: This would produce following result: Exception

Exception thrown thrown :java.lang.ArrayIndexOutOfBoundsException: :java.lang.ArrayIndexOutOfBoundsException: 33 First element value: 6

First element value: 6

The finally statement is executed The finally statement is executed Note the followings:

Note the followings:

• A catch clause cannot exist without a try statement.A catch clause cannot exist without a try statement. •

• It is not compulsory to have finally clauses when ever a try/catch block is present.It is not compulsory to have finally clauses when ever a try/catch block is present. •

• The try block cannot be present without either catch clause or finally clause.The try block cannot be present without either catch clause or finally clause. •

• Any code cannot be present in between the try, catch, finally blocks.Any code cannot be present in between the try, catch, finally blocks.

Declaring you own Exception: Declaring you own Exception:

You can create your own exceptions in Java. Keep the following points in mind when writing You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:

your own exception classes:

• All exceptions must be a child of Throwable.All exceptions must be a child of Throwable. •

• If you want to write a checked exception that is automatically enforced by the Handle orIf you want to write a checked exception that is automatically enforced by the Handle or

Declare Rule, you need to extend the Exception class. Declare Rule, you need to extend the Exception class.

• If you want to write a runtime exception, you need to extend the RuntimeException class.If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below: We can define our own Exception class as below: class MyException extends Exception{

class MyException extends Exception{ }}

(17)

You just need to extend the Exception class to create your own Exception class. These are You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

class is like any other class, containing useful fields and methods.

Example: Example:

 // File Name InsufficientFundsException.java  // File Name InsufficientFundsException.java

import java.io.*; import java.io.*;

public class InsufficientFundsException extends Exception public class InsufficientFundsException extends Exception {{

private double amount; private double amount;

public InsufficientFundsException(double amount) public InsufficientFundsException(double amount) {{

this.amount = amount; this.amount = amount; }}

public double getAmount() public double getAmount() {{

return amount; return amount; }}

}}

To demonstrate using our user-defined exception, the following CheckingAccount class contains To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an

a withdraw() method that throws an InsufficientFundsException.InsufficientFundsException.  // File Name CheckingAccount.java

 // File Name CheckingAccount.java import java.io.*;

import java.io.*;

public class CheckingAccount public class CheckingAccount {{

private double balance; private double balance; private int number; private int number;

public CheckingAccount(int number) public CheckingAccount(int number) {{

this.number = number; this.number = number; }}

public void deposit(double amount) public void deposit(double amount) {{

balance += amount; balance += amount; }}

public void withdraw(double amount) throws public void withdraw(double amount) throws InsufficientFundsException InsufficientFundsException {{

(18)

if(amount <= balance) if(amount <= balance) {{ balance -= amount; balance -= amount; }} else else {{

double needs = amount - balance; double needs = amount - balance;

throw new InsufficientFundsException(needs); throw new InsufficientFundsException(needs); }}

}}

public double getBalance() public double getBalance() {{

return balance; return balance; }}

public int getNumber() public int getNumber() {{

return number; return number; }}

}}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.

of CheckingAccount.

 // File Name BankDemo.java  // File Name BankDemo.java

public class BankDemo public class BankDemo {{

public static void main(String [] args) public static void main(String [] args) {{

CheckingAccount c = new CheckingAccount(101); CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); System.out.println("Depositing $500..."); c.deposit(500.00); c.deposit(500.00); try try {{ System.out.println("\nWithdrawing $100..."); System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); c.withdraw(600.00); }catch(InsufficientFundsException e) }catch(InsufficientFundsException e) {{

System.out.println("Sorry, but you are short $" System.out.println("Sorry, but you are short $"

+ e.getAmount()); + e.getAmount()); e.printStackTrace(); e.printStackTrace(); }} }}

(19)

}}

Compile all the above three files and run BankDemo, this would produce following result: Compile all the above three files and run BankDemo, this would produce following result: Depositing $500... Depositing $500... Withdrawing $100... Withdrawing $100... Withdrawing $600... Withdrawing $600...

Sorry, but you are short $200.0 Sorry, but you are short $200.0 InsufficientFundsException InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13) at BankDemo.main(BankDemo.java:13) Common Exceptions: Common Exceptions:

In java it is possible to define two catergories of Exceptions and Errors. In java it is possible to define two catergories of Exceptions and Errors.

• JVM Exceptions:JVM Exceptions:- These are exceptions/errors that are exclusively or logically thrown- These are exceptions/errors that are exclusively or logically thrown

by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,

ClassCastException,

• Programmatic exceptionsProgrammatic exceptions. These exceptions are thrown explicitly by the application or. These exceptions are thrown explicitly by the application or

the API programmers Examples: IllegalArgumentException, IllegalStateException. the API programmers Examples: IllegalArgumentException, IllegalStateException.

References

Related documents

Valiron (2004a,b) and Selinger &amp; Valiron (2005; 2006) define a higher-order functional programming language based on the idea of classical control and quantum data

Translator is a computer program that translates one programming language instruction(s) into another programming language instruction(s) … A computer source code is to be

IMPERATIVE LANGUAGES 6 the details of assembly language programming by offering structured control statements and data structures (arrays and records), while at the same time it

Programming language paradigm expresses how the languages is designed to be used and in which domains. This also affects how programmers design their programs to

the current continuation is the continuation that, from the perspective of running code, would be derived from the current point in a program execution if the language supports

The course surveys parallel programming platforms, introduces the principles of parallel program design and the concepts of parallel programming models, presents performance

Reasons to Study Programming Language Theory • Increased ability to design new languages?. – You probably will be designing a language of some sort sometime in

Choosing a programming language: Whether it is better to use a ready-made mathematical software package or write a program in a lower level language like C or Fortran depends on