JAVA Developed at SUN by James Gosling with support from Bill Joy Net-based language Descended from Oak » platform independent » object oriented » small The Java Tutorial: http://java.sun.com/docs/books/tutorial Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 1 Goals for Java Simple » easy to learn – based on C/C++ » small Object oriented » single inheritance Distributed Robust strongly typed safe pointer model Secure Platform independent virtual machine Portable no implementation dependent data types » libraries supply protocols Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 2 Goals for Java (cont.) Compiled and interpreted Multithreaded Dynamic Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 3 Java Virtual Machine Compiler translates Java into J-code Stack-based virtual machine (JVM) No undefined or platform specific data types Other languages can be translated to J-code Interpreter is lightweight, easy to implement » use widely available language, like C J-code is highly optimized J-code can be compiled on the fly Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 4 How it Works Java compiler (javac) Java source Platform independent J-code (JVM byte codes) The JVM may be » » » » Native code an interpreter an applet viewer a web browser part of an OS Other classes Dillon: CSE470: JAVA, EXCEPTIONS & THREADS Java interpreter (a JVM) e.g., AWT Platform dependent Classes could be loaded from filesystem or over a network JVMs use an environment variable, CLASSPATH, to find byte code (.class files) to execute 5 Java combines benefits of A strongly typed, OO language Flexibility of an interpreted language » Lisp, Perl, Tcl A smalltalk virtual machine with security protection » Java byte code verifier reduces runtime checks Package structure for organizing classes into subsystems Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 6 Other benefits of Java Exception handling Support for multi-threading » Based on Hoare’s monitors Highly optimized » Easy debugging – make debugging statements dependent on a constant value, which programmer sets when done debugging – compiler automatically removes unexecutable statements Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 7 Three levels of Security Security manager » controls access to system resources » highlight windows of untrusted applications Class loader » restricts classes loaded from network to interact with classes from the same location Verifier » checks that incoming classes can’t forge pointers, violate access permissions, over/under flow operator stack, etc. » ensures type safety Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 8 Java doesn’t have Macros and preprocessor » mostly used for platform dependencies Operator overloading, except for + (Very many) automatic type coercions Pointer arithmetic » references are a higher level type and can only point to class objects, not to class methods Explicit memory management » provides automatic garbage collection Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 9 Java and the Web A web browser can incorporate a JVM and run Java applets as executable code Life of an applet » Loaded by a web browser and asked to initialize itself » Informed each time it is displayed and hidden » Informed when it is no longer needed Security manager prevents applet from accessing system resources or interacting with outside applications Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 10 Java classes Class is the basic computation unit » encapsulates data and associated operations » found and loaded dynamically as needed 22 architecture specific classes: “gateway to the real world” » networking, windowing, filesystem, etc. Rest of Java is written in Java Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 11 Inheritance in Java Single inheritance hierarchy Multiple inheritance of interfaces » Interface specifies the operations but not the implementations » A class can “implement” multiple interfaces Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 12 Java coding conventions Class names begin with upper case letters Variables and method names begin with lower case letters Constants are all upper case Separate words with uppercase letter instead of underscores e.g. aVariableName AClassName aMethodName Dillon: CSE470: JAVA, EXCEPTIONS & THREADS ACONSTANT 13 Classes in Java Define an abstract data type » operations called methods » data called variables or fields Many class instances or objects can exist » each instance may have a different state – e.g., different values for variables » all instances have the same methods Arranged in a hierarchy » each class has a unique superclass (parent) » subclass (child) can add or modify methods or variables of the superclass Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 14 Variables in Java Maintain state of a class instance Belong to some class or class instance » static variable -- one per class » instance variable -- one per class instance All variable values are by reference » point to their values, which are maintained on a heap » Initial value is null » access to null value raises the NullPointerException exception Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 15 A simple Java applet import java.applet.Applet; import java.awt.Graphics; public class Simple extends Applet { StringBuffer buffer; public void init( ) { buffer = new StringBuffer( ); addItem(“initializing …”); } public void start( ) { addItem(“starting …”); } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 16 A simple Java applet (cont.) public void stop( ) { addItem(“stopping …”); } public void destroy( ) { addItem(“starting …”); } public void addItem(String newWord ) { System.out.println(newWord); buffer.append(newWord); repaint( ); } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 17 A simple Java applet (cont.) public void paint (Graphics g) { //Draw a rectangle around the applet’s display area g.drawRectangle(0, 0, size( ).width-1, size( ).height-1); //Draw the current string inside the rectangle g.drawString(buffer.toString( ), 5, 15); } } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 18 Lifetime of an Applet leave page/stop( ) iconify/stop( ) quit/destroy( ) load/init( );start( ); running stopped de-iconify/start( ) reload/stop( ); destroy( ); init( ) return to page/start( ) Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 19 Part of the Java Class Hierarchy Object Component Button Container Window Panel Applet Simple Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 20 Subclassing and Inheritance A subclass extends, refines, or specializes a superclass A subclass can extend only one superclass A subclass inherits the public methods and variables from its superclass » Does not inherit private members (in Java) The subclass is considered a subtype of the superclass » All visible superclass operations apply to subclass Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 21 Subclassing Example Container Container( ) add(Component) doLayout( ) getComponent(int) Window paint(Graphics) print(Graphics) remove(Component) ... Panel Panel( ) Panel(Layout) addNotify( ) Simple Applet Applet( ) init( ) start( ) ... getImage(URL, String) getParameter(String) play(URL) ... Dillon: CSE470: JAVA, EXCEPTIONS & THREADS init( ) start( ) stop( ) destroy ( ) paint (Graphics) 22 Interfaces in Java An interface class describes a protocol of behavior » Members are constants and abstract methods » Abstract methods have no implementations Can be implemented by any class anywhere in the class heirarchy » Cannot be instantiated » Implementing classes agree to implement all methods declared in the interface » Class can implement multiple interfaces » Interface can be implemented by multiple classes Does not force a class relationship Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 23 Interface Example Objects can register themselves with an AlarmClock object to be woken up after some specified time » Objects call the letMeSleepFor method: public synchronized boolean letMeSleepFor( Sleeper theSleeper, long time) { int index = findNextSlot ( ); if (index == NOROOM) { return false; } else { sleepers[ index ] = theSleeper; sleepFor[ index ] = time; new AlarmThread( index ).start( ); return true; } } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 24 Interface Example (cont.) An object that wants to use AlarmClock must implement the wakeUp method » This is enforced by the type of theSleeper Public interface Sleeper { public void wakeUp ( ); public long ONE_SECOND = 1000; public long ONE_MINUTE = 60000; // in milliseconds // in milliseconds } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 25 Interface Example (cont.) Any object that implements this interface can be passed to letMeSleepFor Class GUIClock extends Applet implements Sleeper { . . . public void wakeUp ( ) { repaint ( ); clock.letMeSleepFor( this, ONE_MINUTE); } } GUIClock updates its display every minute (showing the current time) Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 26 Abstract class v.s. Interface class Why not use an abstract class for Sleeper? Abstract class Sleeper { public abstract void wakeUp ( ); } Only objects that are subclasses of Sleeper would be able to use AlarmClock Conceptually, AlarmClock should not force a class relationship on its users Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 27 Exceptional Conditions Handling exceptional conditions can more than double the size of the code Systems can respond to errors in many ways » crash » give error message and crash » give error message and let user retry – minimize work that must be redone – allow user to decide how much work must be redone » correct the error – allow user to confirm that correction is valid Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 28 Approaches for Handling Exceptional Conditions Each method handles the exceptional conditions that arise during its execution A low level class/method handles all exceptional conditions that may arise All methods return status information so that client methods can respond to exceptional conditions ALL OF THESE APPROACHES HAVE PROBLEMS Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 29 I. Each method handles its own exceptional conditions info1 (in case an exception arises) Code to detect and handle exception info1, info2 (in case an exception arises) Code to detect and handle exception (use info1) Code to detect and handle exception (use info1, info2) Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 30 I. Each method handles its own exceptional conditions No modularity or consistency » changes to error handling affect all the methods May need to pass considerable information many levels to maintain context information » hard to provide user friendly response w/o knowing clients context Must return status information so calling method can determine if it should proceed or terminate Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 31 II. A low level class/method handles exceptional conditions Exception handling class Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 32 II. A low level class/method handles exceptional conditions Error processing handled in a more consistent and modular fashion » changes to error handling only affect the error handling class/method May need to pass considerable information many levels to maintain context information » hard to provide user friendly response w/o knowing clients context Must return status information so calling method can determine if it should proceed or terminate Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 33 III. Methods return status information so that client methods can respond to exceptional conditions Calling method must always check status information Calling methods must be able to respond to status information call Foo(bar, status1, status2, …, statusN); if status1 then do repair1; else if status2 then do repair2; else if . . . else normal processing using bar endif Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 34 Exceptions were added to languages to help with error processing A method that detects a problem can handle the exception locally and then raise/throw/signal an exception to the methods in its calling context handler for E1 throw E1 Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 35 A method can catch an exception and specialize its response handler for E2 handler for E1; throw E2 throw E1 Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 36 Exception Handling Mechanisms Signal/raise/throw an exception » predefined » user defined Exception handlers » local » non-local – propagate through call stack – one level only – multiple levels Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 37 Exception Handling Mechanisms (cont.) Execution after handler » resumption model: return to signal location » termination model: terminate execution of method Java supports predefined and user defined exceptions, local and multi-level propagation, with termination Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 38 Exceptions in Java Indicates an unusual situation (error) Thrown at the point in the code where the error occurs Caught by an exception handler » Can be handled locally » Can look back through call stack for the first handler Methods must declare the exceptions they throw Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 39 Handling Exceptions try { i = s.pop( ); } catch( EmptyStackException i); { system.out.println( “Oops! The stack is empty!” ); i = 0; } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 40 Handling multiple exceptions try { readFromFile( “foo” ); } catch( FileNotFoundException e); { system.out.println( “Oops! The file is missing!” ); } catch( IOException e ) { system.out.println( “Oops! Can’t read the file!” ); } finally { readFromFile( “foo.bak”); } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 41 Try/Catch Statement Exceptions raised in the try body are handled in the catch statements Catch statements are evaluated in order » first match leads to execution of the catch body Usually list exceptions from most specific to least specific If there is a finally clause then it is always executed May not execute all statements in try body » could be interrupted by an exception Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 42 Finding Exception Handlers Look in enclosing blocks Look in calling methods If no exception handler is found in call stack, program crashes handler for E1 propagate E1 throw E1 Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 43 Multiple Levels of Propagation getContent( _) { try { openConection( ); readData ( ); } catch (IOException e) { //handle IO error } } openConnection ( ) throws IOException { openSocket( ); sendRequest( ); …. } sendRequest ( ) throws IOException { write (body); //write error } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 44 Explanation Write throws the exception sendRequest doesn’t handle the exception but must indicate that it propagates the exception Same for openConnection getContent catch statement handles the exception May never execute the readData( ) statement in getContent Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 45 Throwing Exceptions int Dequeue (Queue q) throws QueueEmpty { if ( q.head == q.tail ) { throw new QueueEmpty ( ); } else { q.head = q.head + 1; return q.contents [q.head - 1]; } } class QueueEmpty extends Exception { } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 46 Types of Java Exceptions General exceptions » Must be explicitly thrown » Should be handled by all programs Runtime exceptions » Frequent runtime problems » No need to explicitly state that such an exception might be thrown » Runtime message generated if they are not caught Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 47 Summary of Exception Handling Exceptions allow the programmer to separate the handling of unusual cases from expected ones Program should catch predefined exceptions and throw more specific exceptions when possible Exception handling is difficult, even with exception handlers Exception handling is an important part of most programs Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 48 Concurrent System Multiple threads of execution » Logically concurrent: share a single processor » Physically concurrent: multiple processors Run independently, for the most part Typically, need to communicate » Share data » Pass messages Typically, need to synchronize their activities Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 49 Threads in Java A thread is a sequential flow of control within a program » has a beginning, an execution sequence, and an end » cannot be run on its own, but exists only within a larger program A program with three threads Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 50 Defining the behavior of a thread The behavior of a thread in Java is given by a special method » the run method Two techniques for providing a run method for a thread » Subclass Thread and override the run method » Implement the Runnable interface Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 51 Defining thread behavior: Subclassing Thread A thread that computes names larger than a given value class PrimeThread extends Thread { long minPrime; PrimeThread ( long minPrime ) { this.minPrime = minPrime; } public void run ( ) { // compute primes larger than minPrime . . . } } Code to create a PrimeThread thread and start running it: PrimeThread p = new PrimeThread(143); p.start ( ); Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 52 Defining thread behavior: Implementing runnable A thread that computes names larger than a given value class PrimeRun implements Runnable { long minPrime; PrimeRun ( long minPrime ) { this.minPrime = minPrime; } public void run ( ) { // compute primes larger than minPrime . . . } } Code to create a PrimeThread thread and start running it: PrimeRun p = new PrimeRun(143); new Thread( p ).start ( ); Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 53 When should you implement Runnable? If a class needs its own thread and must subclass some other class, you should implement Runnable » Example: Suppose you want an applet that displays the time, updating it every second – It has to subclass Applet to run in a browser – It needs its own thread in order to continuously update its display without taking over the process that its running in Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 54 Life Cycle of a Thread in Java running waiting new Thread ( . . . ) start ( ) new executing not runnable run method terminates stopped Transitions to not runnable » invokes its sleep method » invokes a wait method for some condition » blocks on an IO operation Dillon: CSE470: JAVA, EXCEPTIONS & THREADS Transitions to running » specified time elapses » notify method is invoked to signify the condition is met » the IO operation completes 55 Synchronizing Threads in Java A lock is associated with objects containing synchronized methods » The object is locked when a thread enters one of its synchronized methods » Other threads cannot enter a synchronized method on the same object until the object is unlocked Lock is acquired and released automatically by the Java Runtime System Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 56 Synchronizing Threads in Java (cont.) Threads that use synchronized methods are coordinated using wait and notify (or notifyAll) » Invoking the wait method blocks the thread and releases the lock » An object invokes notify to wake up a thread that is waiting on it Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 57 Producer/Consumer Example public class CubbyHole { private int contents; private boolean available = false; public synchronized int put ( ) { //CubbyHole is locked by the Producer . . . //CubbyHole is unlocked by the Producer } public synchronized int get ( ) { //CubbyHole is locked by the Consumer . . . //CubbyHole is unlocked by the Consumer } } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 58 Producer/Consumer Example (cont.) public synchronized int get ( ) { while ( available == false ) { try { // wait for Producer to put value wait ( ); } catch ( InterruptedException e) { } } available = false; // notify Producer that value has been retrieved notifyAll ( ); return contents; } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 59 Producer/Consumer Example (cont.) public synchronized void put ( int value ) { while ( available == true ) { try { // wait for Consumer to get value wait ( ); } catch ( InterruptedException e) { } } contents = value; available = true; // notify Consumer that value has been set notifyAll ( ); } Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 60 Concurrency Summary A thread is a sequential flow of control Multiple threads execute concurrently within the same program Objects with synchronized methods implement monitors » monitors use the wait and notify methods to coordinate the activities of the threads that they serve Dillon: CSE470: JAVA, EXCEPTIONS & THREADS 61