JAVA Developed at SUN by James Gosling with
JAVA Developed at SUN by James Gosling with support from Bill Joy l Net-based language l Descended from Oak l » platform independent » object oriented » small l The Java Tutorial: http: //java. sun. com/docs/books/tutorial Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 1
Goals for Java l Simple » easy to learn – based on C/C++ » small l Object oriented » single inheritance l Distributed Robust strongly typed safe pointer model Secure Platform independent virtual machine Portable no implementation dependent data types » libraries supply protocols Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 2
Goals for Java (cont. ) l l l Compiled and interpreted Multithreaded Dynamic Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 3
Java Virtual Machine l l l 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 l l J-code is highly optimized J-code can be compiled on the fly Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 4
How it Works Java compiler (javac) Java source Platform independent l 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 l l Dillon: CSE 470: 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 l A strongly typed, OO language l Flexibility of an interpreted language » Lisp, Perl, Tcl l A smalltalk virtual machine with security protection » Java byte code verifier reduces runtime checks l Package structure for organizing classes into subsystems Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 6
Other benefits of Java l Exception handling l Support for multi-threading » Based on Hoare’s monitors l Highly optimized » Easy debugging – make debugging statements dependent on a constant value, which programmer sets when done debugging – compiler automatically removes unexecutable statements Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 7
Three levels of Security l Security manager » controls access to system resources » highlight windows of untrusted applications l Class loader » restricts classes loaded from network to interact with classes from the same location l Verifier » checks that incoming classes can’t forge pointers, violate access permissions, over/under flow operator stack, etc. » ensures type safety Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 8
Java doesn’t have l Macros and preprocessor » mostly used for platform dependencies l l l 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 l Explicit memory management » provides automatic garbage collection Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 9
Java and the Web l l 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 l Security manager prevents applet from accessing system resources or interacting with outside applications Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 10
Java classes l Class is the basic computation unit » encapsulates data and associated operations » found and loaded dynamically as needed l 22 architecture specific classes: “gateway to the real world” » networking, windowing, filesystem, etc. l Rest of Java is written in Java Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 11
Inheritance in Java l Single inheritance hierarchy l Multiple inheritance of interfaces » Interface specifies the operations but not the implementations » A class can “implement” multiple interfaces Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 12
Java coding conventions l l 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. a. Variable. Name a. Method. Name AClass. Name ACONSTANT Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 13
Classes in Java l Define an abstract data type » operations called methods » data called variables or fields l 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 l Arranged in a hierarchy » each class has a unique superclass (parent) » subclass (child) can add or modify methods or variables of the superclass Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 14
Variables in Java l l Maintain state of a class instance Belong to some class or class instance » static variable -- one per class » instance variable -- one per class instance l 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 Null. Pointer. Exception exception Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 15
A simple Java applet import java. applet. Applet; import java. awt. Graphics; public class Simple extends Applet { String. Buffer buffer; public void init( ) { buffer = new String. Buffer( ); add. Item(“initializing …”); } public void start( ) { add. Item(“starting …”); } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 16
A simple Java applet (cont. ) public void stop( ) { add. Item(“stopping …”); } public void destroy( ) { add. Item(“starting …”); } public void add. Item(String new. Word ) { System. out. println(new. Word); buffer. append(new. Word); repaint( ); } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 17
A simple Java applet (cont. ) public void paint (Graphics g) { //Draw a rectangle around the applet’s display area g. draw. Rectangle(0, 0, size( ). width-1, size( ). height-1); //Draw the current string inside the rectangle g. draw. String(buffer. to. String( ), 5, 15); } } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 18
Lifetime of an Applet leave page/stop( ) iconify/stop( ) load/init( ); start( ); running quit/destroy( ) stopped de-iconify/start( ) reload/stop( ); destroy( ); init( ) return to page/start( ) Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 19
Part of the Java Class Hierarchy Object Component Button Container Window Panel Applet Simple Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 20
Subclassing and Inheritance l l l 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) l The subclass is considered a subtype of the superclass » All visible superclass operations apply to subclass Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 21
Subclassing Example Container( ) add(Component) do. Layout( ) get. Component(int) Window paint(Graphics) print(Graphics) remove(Component). . . Panel( ) Panel(Layout) add. Notify( ) Simple Applet( ) init( ) start( ). . . get. Image(URL, String) get. Parameter(String) play(URL) . . . Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS init( ) start( ) stop( ) destroy ( ) paint (Graphics) 22
Interfaces in Java l An interface class describes a protocol of behavior » Members are constants and abstract methods » Abstract methods have no implementations l 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 l Does not force a class relationship Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 23
Interface Example l Objects can register themselves with an Alarm. Clock object to be woken up after some specified time » Objects call the let. Me. Sleep. For method: public synchronized boolean let. Me. Sleep. For( Sleeper the. Sleeper, long time) { int index = find. Next. Slot ( ); if (index == NOROOM) { return false; } else { sleepers[ index ] = the. Sleeper; sleep. For[ index ] = time; new Alarm. Thread( index ). start( ); return true; } } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 24
Interface Example (cont. ) l An object that wants to use Alarm. Clock must implement the wake. Up method » This is enforced by the type of the. Sleeper Public interface Sleeper { public void wake. Up ( ); public long ONE_SECOND = 1000; public long ONE_MINUTE = 60000; // in milliseconds } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 25
Interface Example (cont. ) l Any object that implements this interface can be passed to let. Me. Sleep. For Class GUIClock extends Applet implements Sleeper {. . . public void wake. Up ( ) { repaint ( ); clock. let. Me. Sleep. For( this, ONE_MINUTE); } } GUIClock updates its display every minute (showing the current time) Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 26
Abstract class v. s. Interface class l Why not use an abstract class for Sleeper? Abstract class Sleeper { public abstract void wake. Up ( ); } Only objects that are subclasses of Sleeper would be able to use Alarm. Clock Conceptually, Alarm. Clock should not force a class relationship on its users Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 27
Exceptional Conditions l l 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 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: CSE 470: JAVA, EXCEPTIONS & THREADS 28
Approaches for Handling Exceptional Conditions l l l 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: CSE 470: JAVA, EXCEPTIONS & THREADS 29
I. Each method handles its own exceptional conditions info 1 (in case an exception arises) Code to detect and handle exception info 1, info 2 (in case an exception arises) Code to detect and handle exception (use info 1, info 2) Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 30
I. Each method handles its own exceptional conditions l No modularity or consistency » changes to error handling affect all the methods l May need to pass considerable information many levels to maintain context information » hard to provide user friendly response w/o knowing clients context l Must return status information so calling method can determine if it should proceed or terminate Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 31
II. A low level class/method handles exceptional conditions Exception handling class Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 32
II. A low level class/method handles exceptional conditions l Error processing handled in a more consistent and modular fashion » changes to error handling only affect the error handling class/method l May need to pass considerable information many levels to maintain context information » hard to provide user friendly response w/o knowing clients context l Must return status information so calling method can determine if it should proceed or terminate Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 33
III. Methods return status information so that client methods can respond to exceptional conditions l l Calling method must always check status information Calling methods must be able to respond to status information call Foo(bar, status 1, status 2, …, status. N); if status 1 then do repair 1; else if status 2 then do repair 2; else if. . . else normal processing using bar endif Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 34
Exceptions were added to languages to help with error processing l 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 E 1 throw E 1 Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 35
A method can catch an exception and specialize its response handler for E 2 handler for E 1; throw E 2 throw E 1 Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 36
Exception Handling Mechanisms l Signal/raise/throw an exception » predefined » user defined l Exception handlers » local » non-local – propagate through call stack – one level only – multiple levels Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 37
Exception Handling Mechanisms (cont. ) l Execution after handler » resumption model: return to signal location » termination model: terminate execution of method l Java supports predefined and user defined exceptions, local and multi-level propagation, with termination Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 38
Exceptions in Java l l l 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 l Methods must declare the exceptions they throw Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 39
Handling Exceptions try { i = s. pop( ); } catch( Empty. Stack. Exception i); { system. out. println( “Oops! The stack is empty!” ); i = 0; } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 40
Handling multiple exceptions try { read. From. File( “foo” ); } catch( File. Not. Found. Exception e); { system. out. println( “Oops! The file is missing!” ); } catch( IOException e ) { system. out. println( “Oops! Can’t read the file!” ); } finally { read. From. File( “foo. bak”); } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 41
Try/Catch Statement l Exceptions raised in the try body are handled in the catch statements l Catch statements are evaluated in order » first match leads to execution of the catch body l Usually list exceptions from most specific to least specific l If there is a finally clause then it is always executed l May not execute all statements in try body » could be interrupted by an exception Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 42
Finding Exception Handlers l l l Look in enclosing blocks Look in calling methods If no exception handler is found in call stack, program crashes handler for E 1 propagate E 1 throw E 1 Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 43
Multiple Levels of Propagation get. Content( _) { try { open. Conection( ); read. Data ( ); } catch (IOException e) { //handle IO error } } open. Connection ( ) throws IOException { open. Socket( ); send. Request( ); …. } send. Request ( ) throws IOException { write (body); //write error } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 44
Explanation l Write throws the exception l send. Request doesn’t handle the exception but must indicate that it propagates the exception l Same for open. Connection l get. Content catch statement handles the exception l May never execute the read. Data( ) statement in get. Content Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 45
Throwing Exceptions int Dequeue (Queue q) throws Queue. Empty { if ( q. head == q. tail ) { throw new Queue. Empty ( ); } else { q. head = q. head + 1; return q. contents [q. head - 1]; } } class Queue. Empty extends Exception { } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 46
Types of Java Exceptions l General exceptions » Must be explicitly thrown » Should be handled by all programs l 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: CSE 470: JAVA, EXCEPTIONS & THREADS 47
Summary of Exception Handling l Exceptions allow the programmer to separate the handling of unusual cases from expected ones l Program should catch predefined exceptions and throw more specific exceptions when possible l Exception handling is difficult, even with exception handlers l Exception handling is an important part of most programs Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 48
Concurrent System l Multiple threads of execution » Logically concurrent: share a single processor » Physically concurrent: multiple processors l Run independently, for the most part l Typically, need to communicate » Share data » Pass messages l Typically, need to synchronize their activities Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 49
Threads in Java l 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: CSE 470: JAVA, EXCEPTIONS & THREADS 50
Defining the behavior of a thread l The behavior of a thread in Java is given by a special method » the run method l Two techniques for providing a run method for a thread » Subclass Thread and override the run method » Implement the Runnable interface Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 51
Defining thread behavior: Subclassing Thread l A thread that computes names larger than a given value class Prime. Thread extends Thread { long min. Prime; Prime. Thread ( long min. Prime ) { this. min. Prime = min. Prime; } public void run ( ) { // compute primes larger than min. Prime. . . } } l Code to create a Prime. Thread thread and start running it: Prime. Thread p = new Prime. Thread(143); p. start ( ); Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 52
Defining thread behavior: Implementing runnable l A thread that computes names larger than a given value class Prime. Run implements Runnable { long min. Prime; Prime. Run ( long min. Prime ) { this. min. Prime = min. Prime; } public void run ( ) { // compute primes larger than min. Prime. . . } } l Code to create a Prime. Thread thread and start running it: Prime. Run p = new Prime. Run(143); new Thread( p ). start ( ); Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 53
When should you implement Runnable? l 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: CSE 470: JAVA, EXCEPTIONS & THREADS 54
Life Cycle of a Thread in Java running waiting new Thread (. . . ) start ( ) new not runnable executing run method terminates stopped l Transitions to not runnable » invokes its sleep method » invokes a wait method for some condition » blocks on an IO operation Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS l 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 l 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 l Lock is acquired and released automatically by the Java Runtime System Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 56
Synchronizing Threads in Java (cont. ) l Threads that use synchronized methods are coordinated using wait and notify (or notify. All) » 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: CSE 470: JAVA, EXCEPTIONS & THREADS 57
Producer/Consumer Example public class Cubby. Hole { private int contents; private boolean available = false; public synchronized int put ( ) { //Cubby. Hole is locked by the Producer. . . //Cubby. Hole is unlocked by the Producer } public synchronized int get ( ) { //Cubby. Hole is locked by the Consumer. . . //Cubby. Hole is unlocked by the Consumer } } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 58
Producer/Consumer Example (cont. ) public synchronized int get ( ) { while ( available == false ) { try { // wait for Producer to put value wait ( ); } catch ( Interrupted. Exception e) { } } available = false; // notify Producer that value has been retrieved notify. All ( ); return contents; } Dillon: CSE 470: 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 ( Interrupted. Exception e) { } } contents = value; available = true; // notify Consumer that value has been set notify. All ( ); } Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 60
Concurrency Summary l A thread is a sequential flow of control l Multiple threads execute concurrently within the same program l Objects with synchronized methods implement monitors » monitors use the wait and notify methods to coordinate the activities of the threads that they serve Dillon: CSE 470: JAVA, EXCEPTIONS & THREADS 61
- Slides: 61