240 likes | 353 Views
This lecture delves into two advanced control mechanisms in Java: exception handling and threading. It covers how exceptions are used to manage unusual situations during execution, including defining, throwing, and catching exceptions. The discussion extends to threading concepts, where separate threads of execution can run concurrently, enhancing program efficiency. Key topics include try-catch blocks, exception propagation, checked and unchecked exceptions, and the lifecycle of threads, providing a comprehensive understanding crucial for effective Java application design.
E N D
Advanced Flow of ControlIntroduction • Two additional mechanisms for controlling process execution are exceptions and threads • Lecture focuses on: • exception processing • catching and handling exceptions • creating new exceptions • separate process threads • synchronizing threads • Thread Priority • Grouping Threads
Exceptions • An exception is an object that describes an unusual or erroneous situation • Exceptions are thrown by a program, and may be caught and handled by another part of the program • A program can therefore be separated into a normal execution flow and an exceptionexecutionflow • An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught
Exception Handling • A program can deal with an exception in one of three ways: • ignore it • handle it where it occurs • handle it in another place in the program • The manner in which an exception is processed is an important design consideration
Exception Handling • If an exception is ignored by the program, the program will terminate and produce an appropriate message • The message includes a call stack trace that indicates on which line the exception occurred • The call stack trace also shows the method call trail that lead to the execution of the offending line • See Zero.javaThe Application
The try Statement • To process an exception when it occurs, the line that throws the exception is executed within a tryblock • A try block is followed by one or more catchclauses, which contain code to process an exception • Each catch clause has an associated exception type • When an exception occurs, processing continues at the first catch clause that matches the exception type • See Adding.javaThe Application
Exception Propagation • If it is not appropriate to handle the exception where it occurs, it can be handled at a higher level • Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the outermost level • A try block that contains a call to a method in which an exception is thrown can be used to catch that exception • See Propagation_Demo.java The Application
Exceptions • Exceptions can be RuntimeExceptions (defined in java.lang) or non- Runtime exceptions such IO exceptions • Runtime exceptions are those exceptions that occur within the Java runtime system. • This includes arithmetic exceptions (such as when dividing by zero), pointer exceptions (such as trying to access an object through a null reference), and indexing exceptions (such as attempting to access an array element through an index that is too large or too small).
Exceptions • An exception is either checkedor unchecked • A checked exception (non-RuntimeExceptions) can only be thrown within a try block or within a method that is designated to throw that exception. • IO exceptions are checked (IOException classes in java.io and java.net) • Checked exceptions must be listed in the method’s throws clause. Echo.java • The compiler will complain if a checked exception is not specified in the throws clause • An unchecked exception does not require explicit handling, though it could be processed that way
The throw Statement • A programmer can define an exception by extending the appropriate class • Exceptions are thrown using the throw statement: throw exception-object; • See Throw_Demo.java The Application • Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown
The finally Clause • A try statement can have an optional clause designated by the reserved word finally • If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete • Also, if an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete
Threads • Processing can be broken into several separate threads of control which execute at the same time • "At the same time" could mean true parallelism or simply interlaced concurrent processing • A thread is one sequential flow of execution that occurs at the same time another sequential flow of execution is processing the same program • They are not necessarily executing the same statements at the same time See the Threads linkThe life-Cycle of a Thread
Threads • A thread can be created by deriving a new thread from the Thread class • The run method of the thread defines the concurrent activity, but the start method is used to begin the separate thread process • See Simultaneous.javaThe Application • A thread can also be created by defining a class that implements the Runnable interface • By implementing the interface, the thread class can be derived from a class other than Thread • See the Threads tutorial link
Shared Data • Potential problems arise when multiple threads share data • Specific code of a thread may execute at any point relative to the processing of another thread • If that code updates or references the shared data, unintended processing sequences can occur that result in incorrect results
task: withdraw 300 Is amount <= balance YES balance -= 300 balance 531 231 -69 task: withdraw 300 Is amount <= balance YES balance -= 300 Shared Data • Consider two withdrawals from the same bank account at the same time
Synchronization • Multiple threads of control can be made safe if areas of code that use shared data are synchronized • When a set of code is synchronized, then only one thread can be using that code at a time • The other threads must wait until the first thread is complete • This is an implementation of a synchronization mechanism called a monitor • See ATM_Accounts.javaThe Application
Controlling Threads • Thread processing can be temporarily suspended, then later resumed, using methods from the Thread class • A thread can also be put to sleep for a specific amount of time • These mechanisms can be quite helpful in certain situations, like controlling animations • See Bouncing_Ball2.javaThe Applet
Thread Priority • The Java runtime supports a very simple, deterministic CPU scheduling algorithm known as fixed priority scheduling • This algorithm schedules threads based on their priority relative to other runnable threads • When a Java thread is created, it inherits its priority from the thread that created it • Thread priorities are integers ranging between MIN_PRIORITY (0) and MAX_PRIORITY (10) • You can modify a thread's priority at any time after its creation using the setPriority method of the Thread class
Thread Priority • the runtime system chooses the runnable thread with the highest priority for execution • If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a round-robin fashion • The chosen thread will run until one of the following conditions is true: • A higher priority thread becomes runnable. • It yields, or its run method exits. • On systems that support time-slicing, its time allotment has expired
Thread Priority • The Java runtime system's thread scheduling algorithm is also preemptive. If at any time a thread with a higher priority than all other runnable threads becomes runnable, the runtime system chooses the new higher priority thread for execution • you should try to write "well-behaved" threads that voluntarily relinquish the CPU periodically and give other threads an opportunity to run • you should never write Java code that relies on time-sharing--this will practically guarantee that your program will give different results on different computer systems.
Synchronizing Threads • The Producer/Consumer Example • Using the notifyAll and wait Methods • Avoid Starvation and Deadlock
Grouping Threads • Every Java thread is a member of a thread group • Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually • the runtime system automatically places the new thread in the same group as the thread that created it (known as the current thread group • When a Java application first starts up, the Java runtime system creates a ThreadGroup named main
Grouping Threads • If you create a thread within an applet, the new thread's group may be something other than main, depending on the browser or viewer that the applet is running • Many browsers allocate a thread for each applet on a page. Some browsers allocate a thread group for each applet, so that it's easy to kill all the threads that belong to a particular applet • In any case, you're guaranteed that every thread that any of an applet's major milestone methods creates belongs to the same thread group
Grouping Threads • Creating a Thread Explicitly in a Group ThreadGroup myThreadGroup = new ThreadGroup("My Group of Threads"); Thread myThread = new Thread(myThreadGroup, "a thread for my group"); • Methods that Operate on All Threads within a Group The ThreadGroup class has three methods that allow you to modify the current state of all the threads within that group: • resume • stop • suspend