Anda di halaman 1dari 7

Lecture Outline

• Java: COOL on steroids


– History
Java • Arrays
• Exceptions
• Interfaces
Lecture 18
• Coercions
• Threads
• Dynamic Loading & Initialization
• Summary
Prof. Aiken CS 143 Lecture 18 1 Prof. Aiken CS 143 Lecture 18 2

Java History The People

• Began as Oak at SUN • James Gosling


– Originally targeted at set-top devices – Principal designer
– Initial development took several years (‘91-’94) – CMU Ph.D.

• Bill Joy
• Retargeted as the Internet language (‘94-95) – ABD from Berkeley (Unix)
– Every new language needs a “killer app”
– Beat out TCL, Python • Guy Steele
– ActiveX came later – MIT PhD
– Famous languages researcher

Prof. Aiken CS 143 Lecture 18 3 Prof. Aiken CS 143 Lecture 18 4

Influences Java Design

• Modula-3 • From our perspective, COOL plus


– types – Exceptions
– Interfaces
• Eiffel, Objective C, C++ – Threads
– Object orientation, interfaces – Dynamic Loading
– Other less important ones . . .

• Lisp
• Java is a BIG language
– Java’s dynamic flavor (lots of features)
– Lots of features
– Lots of feature interactions
Prof. Aiken CS 143 Lecture 18 5 Prof. Aiken CS 143 Lecture 18 6

1
Arrays Subtyping In Java

Assume B < A. What happens in the following?


B<A if B inherits from A as in Cool
B[] b = new B[10]; C<A if C < B and B < A as in Cool
A[] a = b; B[] < A[] if B < A not as in Cool

a[0] = new A();


b[0].aMethodNotDeclaredInA(); This last rule is unsound!

Prof. Aiken CS 143 Lecture 18 7 Prof. Aiken CS 143 Lecture 18 8

What’s Going On? The Right Solution

B[] b = new B[10]; • Disallow subtyping through arrrays


A[] a = b; • Standard solution in several languages
a[0] = new A();
b[0].aMethodNotDeclaredInA(); B<A if B inherits from A
a b C<A if C < B and B < A
B[] < A[] if B = A

Having multiple aliases to updateable locations with


different types is unsound
Prof. Aiken CS 143 Lecture 18 9 Prof. Aiken CS 143 Lecture 18 10

The Java Solution A Common Problem

• Java fixes the problem by checking each array • Deep in a section of code, you encounter an
assignment at runtime for type correctness unexpected error
– Is the type of the object being assigned – Out of memory
compatible with the type of the array? – A list that is supposed to be sorted is not
– etc.
• Huge overhead on array computations!
• What do you do?
• But note: arrays of primitive types unaffected
– Primitive types are not classes

Prof. Aiken CS 143 Lecture 18 11 Prof. Aiken CS 143 Lecture 18 12

2
Exceptions Example

• Add a new type (class) of exceptions class Foo {


public static void main(String[] args) {
try { X(); } catch (Exception e) {
• Add new forms
System.out.println(“Error!”) } }
try { something } catch(x) { cleanup }
throw exception
public void X() throws MyException {
throw new MyException();
}
}

Prof. Aiken CS 143 Lecture 18 13 Prof. Aiken CS 143 Lecture 18 14

Semantics (pseudo-Java) Semantics (Cont.)

T(o) = an exception that has been thrown


o = an ordinary object E├ e o
E ├ throw e  T(o)
E ├ e1  o
E ├ try { e1 } catch(x) { e2 }  o
E ├ ee1  T(o)
E ├ e1  T(o1 ) E ├ ee1  e2  T(o)
E[x  o1 ] ├ ee2  o2 All forms except catch propagate thrown exceptions
E ├ try { e1 } catch(x) { e2 }  o2

Prof. Aiken CS 143 Lecture 18 15 Prof. Aiken CS 143 Lecture 18 16

Simple Implementation Trivia Question

• When we encounter a try


– Mark current location in the stack
What happens to an uncaught exception thrown
• When we throw an exception during object finalization?
– Unwind the stack to the first try
– Execute corresponding catch

• More complex techniques reduce the cost of


try and throw
Prof. Aiken CS 143 Lecture 18 17 Prof. Aiken CS 143 Lecture 18 18

3
Type Checking Interfaces

• Methods must declare types of exceptions • Specify relationships between classes without
they may raise inheritance
public void X() throws MyException
– Checked at compile time
interface PointInterface { void move(int dx, int dy); }
– Some exceptions need not be part of the method signature
• e.g., dereferencing null
class Point implements PointInterface {
• Other mundane type rules void move(int dx, int dy) { … }
– throw must be applied to an object of type Exception }

Prof. Aiken CS 143 Lecture 18 19 Prof. Aiken CS 143 Lecture 18 20

Interfaces Why is this Useful?

“Java programs can use interfaces to make it • A graduate student may be both an University
unnecessary for related classes to share a common employee and a student
abstract superclass or to add methods to Object.”

class GraduateStudent implements Employee,


In other words, interfaces play the same role as
Student { … }
multiple inheritance in C++, because classes
can implement multiple interfaces
• No good way to incorporate Employee, Student
class X implements A, B, C { … }
methods for grad students with single
inheritance
Prof. Aiken CS 143 Lecture 18 21 Prof. Aiken CS 143 Lecture 18 22

Implementing Interfaces Implementing Interfaces (Cont.)

• Methods in classes implementing interfaces need not • Dispatches e.f(…) where e has an interface
be at fixed offsets. type are more complex than usual
– Because methods don’t live at fixed offsets
interface PointInterface { void move(int dx, int dy); }

• One approach:
class Point implements PointInterface {
– Each class implementing an interface has a lookup
void move(int dx, int dy) { … } } table method names  methods
class Point2 implements PointInterface { – Hash method names for faster lookup
void dummy() { … } • hashes computed at compile time
void move(int dx, int dy) { … } }
Prof. Aiken CS 143 Lecture 18 23 Prof. Aiken CS 143 Lecture 18 24

4
Coercions Coercions & Casts

• Java allows primitive types to be coerced in • Java distinguishes two kinds of coercions &
certain contexts. casts:
– Widening always succeed (int  float)
• In 1 + 2.0, the int 1 is widened to a float 1.0 – Narrowing may fail if data can’t be converted to
desired type (float  int, downcasts)

• A coercion is really just a primitive function • Narrowing casts must be explicit


the compiler inserts for you
– Most languages have extensive coercions between
base numeric types • Widening casts/coercions can be implicit

Prof. Aiken CS 143 Lecture 18 25 Prof. Aiken CS 143 Lecture 18 26

Trivia Question Coercions in PL/I

• Let A,B,C be strings of 3 characters.

B = ‘123’
What is the only type in Java for which there C = ‘456’
are no coercions/casts defined? A=B+C

• What is A?

Prof. Aiken CS 143 Lecture 18 27 Prof. Aiken CS 143 Lecture 18 28

Threads Example (from the Java Spec)

• Java has concurrency built in through threads class Simple {


int a = 1, b = 2;
• Thread objects have class Thread void to() { a = 3; b = 4; }
– Start and stop methods void fro() {println("a= " + a + ", b=" + b); }
}
• Synchronization obtains a lock on the object:
synchronized { e } Two threads call to() and fro(). What is
• In synchronized methods, this is locked printed?

Prof. Aiken CS 143 Lecture 18 29 Prof. Aiken CS 143 Lecture 18 30

5
Example (Cont.) Example (Cont.)

class Simple { class Simple {


int a = 1, b = 2; int a = 1, b = 2;
void synchronized to() { a = 3; b = 4; } void synchronized to() { a = 3; b = 4; }
void fro() {println("a= " + a + ", b=" + b); } void synchronized fro() {println("a= " + a + ",
} b=" + b); }
}
Two threads call to() and fro(). What is
printed? Two threads call to() and fro(). What is
printed?
Prof. Aiken CS 143 Lecture 18 31 Prof. Aiken CS 143 Lecture 18 32

Semantics Dynamic Loading

• Even without synchronization, a variable • Java allows classes to be loaded at run time
should only hold values written by some thread – Type checking source takes place at compile time
– Writes of values are atomic – Bytecode verification takes place at run time
– Violated for doubles, though
• Loading policies handle by a ClassLoader
• Java concurrency semantics are difficult to
understand in detail, particularly as to how • Classes may also be unloaded
they might be implemented on certain
– But poorly specified in the definition
machines

Prof. Aiken CS 143 Lecture 18 33 Prof. Aiken CS 143 Lecture 18 34

Initialization Class Initialization Procedure (Partial)

• Initialization in Java is baroque 1. Lock the class object for the class
– Everything in COOL plus much more • Wait on the lock if another thread has locked it
– Greatly complicated by concurrency 2. If the same thread is already initializing this
class, release lock and return
• A class is initialized when a symbol in the class 3. If class already initialized, return normally
is first used 4. Otherwise, mark initialization as in progress
– Not when the class is loaded by this thread and unlock class
– Delays initialization errors to a predictable point
(when something in the class is referenced)

Prof. Aiken CS 143 Lecture 18 35 Prof. Aiken CS 143 Lecture 18 36

6
Class Initialization (Cont.) Features and Feature Interactions

5. Initialize superclass, fields (in textual order) • In any system with N features, there are
• But initialize static, final fields first potentially N2 feature interactions.
• Give every field a default value before
initialization
• Big, featureful systems are hard to
6. Any errors result in an incorrectly initialized understand!
class, mark class as erroneous – Including programming languages
7. If no errors, lock class, label class as
initialized, notify threads waiting on class
object, unlock class

Prof. Aiken CS 143 Lecture 18 37 Prof. Aiken CS 143 Lecture 18 38

Summary

• Java is pretty well done


– By production language standards, very well done

• Java brings many important ideas into the mainstream


– Strong static typing
– Garbage collection

• But Java also


– Includes many features we don’t understand
– Has a lot of features

Prof. Aiken CS 143 Lecture 18 39