Exceptions and Threads CS212 summer 2003 /**********************************************************************/ Advanced Flow of Control I) MAIN CONCEPTS A) exceptions (helps handle "problems") (Savitch: Chapter 8) B) threads (helps allow simultaneous tasks) (Savitch???) II) "PROBLEMS" WITH PROGRAMS A) Meaning -- when programmer or user does something illegal B) Exception 1. object that defines an unusal or erroneous situation 2. the program or runtime environment "throws" an exception 3. something catches the exception 4. then the "something" handles the exception C) Error 1. like exception, but the program can't recover 2. usually nothing catches an error, since it indicates a very serious problem D) Throwable class 1. superclass for Exception and Error classes 2. see API for many exceptions and errors E) Why bother? 1. helps debug 2. helps prevent crashes 3. makes more code easier to read/understand by moving error checking out of "important" code III) EXCEPTIONS A) Approaches 1. dont handle 2. handle where it occurs 3. handle elsewhere in program B) Not Handle 1. exception gets thrown up the call stack until program aborts 2. program produces a message that tries to explain the problem ex) divide by zero /**********************************************************************/ Example) // except1.java // not handle exceptions public class except1 { public static void main(String args[]) { int a = 1; int b = 0; System.out.println(a/b); // can't divide by zero } } Output: java.lang.ArithmeticException: / by zero -> reason for exception at except1.main(Compiled Code) -> call stack trace /**********************************************************************/ C) Handle exception when/where it occurs 1. use try statement: try { } 2. Java will "try" statements that might issue an exception 3. if issue, or "throw", an exception, then use catch clauses to handle different possibilities 4. use series of catch ( ) { statements } to handle different kinds of exceptions a. try throws exceptions -- catch catches them b. control goes to 1st catch clause whose exception_class matches the exception. Write catch statements beginning as specific as possible, then more general (based on the type of exception) c. each catch clause called an "exception handler" d. see also "finally", which goes after all catch statements 5. if no exceptions or catch clauses handle exception, flow goes to next statement after all the catch clauses 6. call stack trace a. where the exception occurred b. can manually print reason for exception with getMessage() c. can manually print stack trace with printStackTrace() 7. EXAMPLE: see except2.java D) Catch and handle exception somewhere else 1. Method propogation a. exception is thrown b. no catch block catches it c. control returned to method that made the initial call d. Java hopes that the calling method can catch the exception e. if the calling method won't catch, then the method that called the first method tries to catch. f. Java is very optimistic g. the process continues up until main method 2. Appropriate level? a. Programmer considers which level to catch exception b. EXAMPLE: see except3.java E) Who checks for exceptions? 1. some by compiler a. you must deal with exception b. or you can throw the exception c. ex) IOException e. throws {} f. means method will continue to propogate a checked exception d. ex) often seen in main(String args[]) throws IOException 2. Why should compiler check for "checked exceptions"? a. many methods could fail (like built-in methods from API) b. Java wants your program to succeed w/o break in flow c. so, checked exceptions by the comiler forces the programmer to account for things that may go wrong d. use try/catch and throws 3. some unchecked a. your program not need to deal with them 4. see except4.java F) Other features 1. throw a. causes an exception to propogate b. can customize exceptions 2. finally { } a. can be last clause in try statement b. will execture no matter how try is exited IV) THREADS (aka "lightweight processes") A) Normal flow (a single thread) 1. Sequential 2. program goes top-to-bottom 3. statements executed in given order 4. first type of programming you learn. You already know single-threaded programming! B) Having threads 1. concurrent flow 2. different tasks exceute at the same time 3. think "parallel processing" C) Multithreaded 1. formal definition of program with threads 2. each thread is a sequential flow of execution 3. not necessarily executing the same statements D) Creating threads 1. two ways to create a thread: a. extend Thread class and override its run() method b. create a class that implements Runnable interface and pass that object to to the constructor of newly created Thread object 3. Which way should I use? - if your class must subclass (extend) another class, you'll have to implement the Runnable interface. Otherwise, you can extend the Thread class 2. EXAMPLE of (1a): thread1.java a. run method: tells Java what is concurrent b. start method: tells Java to start running a new thread 3. Beware of threads that share data! 4. Deadlock: occurs when multiple threads are waiting on multiple objects, but no thread can get all objects it needs to continue executing. The threads are frozen, waiting for objects that other threads control and will not relinquish - can either prevent or detect deadlock. Your best option is to PREVENT deadlock by imposing an order in which threads acquire locks on objects E) Synchronization 1. Two threads that access and modify data in an object must be synchronized, so that the data is not corrupted (one thread could get inconsistent data if the other thread is not finished writing new data) - Race conditions: two threads both accessing the same data at the same time, asynchronously, and getting the wrong result 2. modify definition of method with the "synchronized" keyword 3. only one "synchronized" method in each object can be called at a time. 4. prevents sharing of data at same time by locking the object (you can also say that the method obtains ownership of the object's monitor; the monitor controls access to the object). F) Controlling threads 1. start(): starts the thread. This method calls the run() method, which you write. 2. getPriority(), setPriority(int): get or set the thread's priority. 1 is lowest, 10 is highest. The computer will give preference to running threads with higher prioties. 3. wait(): makes the thread wait until another thread calls notify() or notifyAll() for this object. The thread waits on the object it is called from. It must be called from a synchronized instance method of the object, or in the body of a synchronized statement that synchronizes on the object. For example: synchronized(myObject) { //some code while(iShouldBeWaiting) { try { wait(); //keep waiting until notified } catch(InterruptedException e) {} } //some more code } 4. notify(): wakes up a single thread that is waiting on this object. The thread is chosen at the discretion of the implementation. 5. notifyAll(): wakes up ALL threads waiting on this object. 6. sleep(): makes the thread sleep for a specified amount of time 7. DO NOT use the methods suspend(), stop(), or resume(). They are unsafe and can lead to deadlocks, damaged objects and data, and arbitrary behavior of your program Example: "producer / consumer" from: java.sun.com/docs/books/tutorial/essential/threads/synchronization.html