Title: JAVA
1JAVA
- 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
2Goals for Java
- Simple
- easy to learn
- based on C/C
- small
- Object oriented
- single inheritance
- Distributed
- libraries supply protocols
Robust strongly typed safe pointer
model Secure Platform independent virtual
machine Portable no implementation dependent data
types
3Goals for Java (cont.)
- Compiled and interpreted
- Multithreaded
- Dynamic
4Java 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
5How it Works
Java compiler (javac)
Java source
Native code
e.g., AWT
Java interpreter (a JVM)
Platform dependent
Platform independent
- The JVM may be
- an interpreter
- an applet viewer
- a web browser
- part of an OS
- Classes could be loaded from filesystem or over a
network - JVMs use an environment variable, CLASSPATH, to
find byte code (.class files) to execute
6Java 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
7Other benefits of Java
- Exception handling
- Support for multi-threading
- Based on Hoares monitors
- Highly optimized
- Easy debugging
- make debugging statements dependent on a constant
value, which programmer sets when done debugging - compiler automatically removes unexecutable
statements
8Three 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 cant forge
pointers, violate access permissions, over/under
flow operator stack, etc. - ensures type safety
9Java doesnt 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
10Java 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
11Java 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
12Inheritance in Java
- Single inheritance hierarchy
- Multiple inheritance of interfaces
- Interface specifies the operations but not the
implementations - A class can implement multiple interfaces
13Java 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 ACONSTANT
-
14Classes 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
15Variables 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
16A 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 )
17A 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( )
18A simple Java applet (cont.)
public void paint (Graphics g)
//Draw a rectangle around the applets 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)
19Lifetime of an Applet
leave page/stop( )
iconify/stop( )
quit/destroy( )
load/init( )start( )
running
stopped
de-iconify/start( )
return to page/start( )
reload/stop( ) destroy( ) init( )
20Part of the Java Class Hierarchy
Object
Component
Container
Button
Window
Panel
Applet
Simple
21Subclassing 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
22Subclassing Example
Container
Container( ) add(Component) doLayout(
) getComponent(int)
paint(Graphics) print(Graphics) remove(Component)
. . .
Panel
Window
Panel( ) Panel(Layout) addNotify( )
Simple
Applet
getImage(URL, String) getParameter(String) play(U
RL) . . .
Applet( ) init( ) start( ) . . .
init( ) start( ) stop( ) destroy ( ) paint
(Graphics)
23Interfaces 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
24Interface 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
25Interface 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
// in milliseconds public long
ONE_MINUTE 60000 // in milliseconds
26Interface 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)
27Abstract 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
28Exceptional 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
29Approaches 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
30I. Each method handles its own exceptional
conditions
info1 (in case an exception arises)
info1, info2 (in case an exception arises)
Code to detect and handle exception
Code to detect and handle exception (use info1)
Code to detect and handle exception (use info1,
info2)
31I. 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
32II. A low level class/method handles exceptional
conditions
Exception handling class
33II. 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
34III. 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
35Exceptions 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
36A method can catch an exception and specialize
its response
handler for E2
handler for E1 throw E2
throw E1
37Exception Handling Mechanisms
- Signal/raise/throw an exception
- predefined
- user defined
- Exception handlers
- local
- non-local
- propagate through call stack
- one level only
- multiple levels
38Exception 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
39Exceptions 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
40Handling Exceptions
try i s.pop( ) catch(
EmptyStackException i)
system.out.println( Oops! The stack
is empty! ) i 0
41Handling multiple exceptions
try readFromFile( foo ) catch(
FileNotFoundException e)
system.out.println( Oops! The file is
missing! ) catch( IOException e )
system.out.println( Oops! Cant read
the file! ) finally readFromFile(
foo.bak)
42Try/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
43Finding 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
44Multiple 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
45Explanation
- Write throws the exception
- sendRequest doesnt 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
46Throwing 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
47Types 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
48Summary 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
49Concurrent 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
50Threads 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
51Defining 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
52Defining 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 ( )
53Defining 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 ( )
54When 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
55Life Cycle of a Thread in Java
running
waiting
new Thread ( . . . )
start ( )
not runnable
new
executing
run method terminates
stopped
- Transitions to not runnable
- invokes its sleep method
- invokes a wait method for some condition
- blocks on an IO operation
- Transitions to running
- specified time elapses
- notify method is invoked to signify the condition
is met - the IO operation completes
56Synchronizing 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
57Synchronizing 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
58Producer/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
59Producer/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
60Producer/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 ( )
61Concurrency 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