Anda di halaman 1dari 8

Java white paper description

 simple
Java for Network Programming  object-oriented

David L. Levine  distributed


Washington University,St. Louis  interpreted
levine@cs.wustl.edu
 robust

 secure

1 2

Java white paper description,


cont'd Similarities with C++
 architecture neutral  syntax

 portable  primitive data types (except that char is


Unicode)
 high-performance
 control ow constructs and operators
 multithreaded  // and /* ::: */ for comments
 dynamic /** ::: */ for javadoc comments

3 4
Di erences from C++ Di erences from C++, cont'd
 not just a language, but an entire execu-  no preprocessor
tion environment
no macros, no #de ne'd constants, no #include
 has:  methods are not explicitly declared virtual
separate interface and implementation inheritance, public and non- nal methods are virtual
threads, exception handling
 does not have:  abstract instead of = 0 for pure virtual
methods
separate class declaration, pointers,
globals, structures, unions, enumerated types,
typedefs, templates, operator overloading
 limited access to underlying system (through
 single implementation inheritance System Properties)
no getenv()
multiple interface inheritence

5 6

References (object and array)


Java memory management
 object and array variables are references
no & or *  must dynamically allocate instances via op-
{ erator new
{ no pointer arithmetic or sizeof except of primitive (not object or array) types
{ eld access is always via \."
 no allocation o stack
{ assignment: use clone() instead of =
{ equality: use equals() instead of ==  no explicit deallocation
{ all objects are reference counted
 a variable equal to null doesn't refer to { when its reference count goes to 0, garbage
any object collector can deallocate an object

 object and array parameters passed by ref-


erence, e.g.,  can manually invoke garbage collector (Sys-
tem.gc())
public static void doublebu er (StringBu er s) f
s.append (s); // side-e ect: modi es s
g
7 8
De ning Java classes Application Programming
/**
* Example class with both implementation and interface inheritance.
*
Interface (API)
* @author Wild Hacker

package lang
* @version 0.1
*/ 
public class Foo extends Bar implements Baz
{
/** { Object, Class, Thread, Math
* constructor: accesses private instance member

System, Runtime, Process


*
* @param x argument of primitive type is passed by value {
*/
public Foo (int x)
{ { Throwable (Exceptions, Errors)
super( x ); // calls Bar constructor

x += foo_int_; // no side-effect { shadows of primitive data types


}

/** { String and StringBu er


* static method: does not access any instance fields
*
* @param s argument of object type is passed by reference
*/
public static void doublebuffer (StringBuffer s)  package io
{
s.append (s); // side-effect
} streams and les
package net
// the class instance is allocated at class load time . . .
private static Foo foo_ = new Foo (); 
private int foo_int_ = 21;

} sockets, URLs, Internet addresses


9 10

java.io package
API, cont'd
 System.out.println (\hello");
 package util
 le output
BitSet, Date, Hashtable, Vector, Stack, etc.
{ FileOutputStream
 package applet { PrintStream
{ extend class Applet
{ security restrictions: limited access to environ-  le input
ment
{ FileInputStream
{ init() entry point instead of main()
{ DataInputStream

 AWT (Abstract Windowing Toolkit)  layer streams (System.in is an InputStream)


DataInputStream in = new DataInputStream (System.in);
String input = in.readLine();
11 12
Thread synchronization
 synchronized keyword
java.Lang.Thread class { synchronized method
 states monitor grants thread exclusive access for
invoking object
new, runnable, blocked, dead { synchronized class (static) method
monitor grants thread exclusive access for
 java.lang.thread package all class static objects
{ synchronized statement
critical section around object or array
 always construct with String name
 java.lang.object methods
 always call start() { wait()

in turn calls run() { timed wait()


no indication of timeout
{ notify() or notifyAll()
13 14

Thread scheduling
 scheduling is implementation dependent Thread groups
{ cooperative on Solaris 2.x
{ time-sliced on Windows  a Thread is always constructed in a Thread-
Group
 priorities
 can specify other than the (default) main
{ MIN PRIORITY == 1 Thread
{ NORM PRIORITY == 5
 can perform operations on all Threads in
{ MAX PRIORITY == 10 a ThreadGroup
daemonize, suspend, resume, stop
 ThreadLister utility

15 16
Example: Moderator Thread
import java.util.Enumeration;
import java.util.Hashtable;
import java.io.*;

Example: Debate /**


* Debate moderator
import java.util.Hashtable; */
public class Moderator extends Thread
/** {
* example threaded program private Moderator( String name )
*/ {
public class Debate super (name);
{ }
/**
* entry point /**
* * accessor for the Singleton moderator
* @param argv currently unused */
*/ public static Moderator getModerator ()
public static void main (String[] argv) {
{ return _theModerator;
Moderator moderator = Moderator.getModerator (); }

moderator.addDebater ("Clinton", "ten million new jobs"); /**


moderator.addDebater ("Dole", "liberal!"); * add a debater
*
moderator.start(); * @param name the debater's name
} * @to_say the debater's (scripted) text
} */
public void addDebater( String name, String to_say )
{
Redemopublicrat debater = new Redemopublicrat (name, to_say);

_debaters.put ("Mr. " + name, debater);


}

17 18

Example: Debater
Example: Moderator, cont'd import java.io.*;

public class Redemopublicrat extends Thread


/** {
* Thread run loop public Redemopublicrat( String name, String to_say )
*/ {
public void run() super (name);
{ setDaemon (true); // don't wait for me when debate ends!
Enumeration debaters = _debaters.elements (); _sez = to_say;
while (debaters.hasMoreElements()) }
{
((Redemopublicrat) debaters.nextElement ()).start(); public void run()
yield(); // let the debater initialize itself {
} while (true)
{
for (int i = 0; i < 10; ++i) waitForModerator();
{ System.out.println (getName() + ": " + _sez);
debaters = _debaters.keys (); }
while (debaters.hasMoreElements ()) }
{
String name = (String) debaters.nextElement (); /**
Redemopublicrat debator = * accept indication (from Moderator) that we can continue
(Redemopublicrat) _debaters.get (name); */
public synchronized void go()
System.out.println (getName() + ": " + name); {
debator.go (); notify();
yield(); }
}
} private synchronized void waitForModerator()
} {
try { wait(); } catch ( InterruptedException interruption )
static private Moderator _theModerator = new Moderator ("Lehrer"); { // ignore interruption }
static private Hashtable _debaters = new Hashtable(); }
}
private String _sez;
}

19 20
Exceptions and Errors
Exceptions and Errors, cont'd
 Exceptions must be caught or thrown
 example of user-de ned Exception:
 Errors and RuntimeExceptions need not
be handled: they get passed up the call public class InvalidDebaterException extends Exception
{

stack /**
* Constructor.
*
* @param debater the name of the invalid debater
*/
 all have getMessage() method for retriev- public InvalidDebaterException (String debater)
{
ing message String }
super (debater);

 all have printStackTrace() method

21 22

Idioms
java.net package  can have main() for each class, for testing

 provides passive ServerSocket and active  toString() method permits implicit con-
Socket classes version

 transparent hostname resolution  String, Vector, Hashtable

 java.io streams can be layered on top of  Threads


socket's InputStream and OutputStreams { avoid sleep() to avoid polling
{ avoid priorities to not depend on scheduler
 all socket operations are blocking
{ match every wait() with a notify()
 there is no select()
 to pass primitive types by reference, put
into array and pass that
23 24
Performance Using Java
 declare classes or methods nal to enable
inlining  only one (public) class per le

 use StringBu er for Strings that need to  javac foo.java


be modi ed
 java foo
 classes are loaded dynamically on demand: { entry point in class foo:
timing should be measured after all classes public static void main (String[] argv) f::: g
are loaded
 disassembler: javap -c foo.class
 just-in-time compilers
 debugger: jdb foo
 native methods are supported

25 26

CLASSPATH
 environment variable or command line ar-
Packages
gument
 name with package statement
 contains any number of directories
colon separated on UNIX, semicolon on Windows  naming convention: EDU.wustl.cs.544.< ::: >

 directories searched for root of a package  access other packages with import state-
hierarchy ment
if package EDU.wustl.cs.544.user.utils is rooted import EDU.wustl.cs.544.user.utils.*;
at /home/user/classes/cs544/java, then
CLASSPATH should contain
.:/home/user/classes/cs544/java

27 28
Javadoc
 for documenting public classes, methods,
and data members
Javadoc special tags
{ package listing
 @version (does not seem to work?)
{ package tree
{ name index
 @author (does not seem to work?)
{ detailed descriptions
 @see classname
 javadoc [-d directory] package/ le names
 @param name description
 start javadoc comment: /**
 @exception name description
 end javadoc comment: */
 @return description
 can contain most HTML tags and special
tags
29 30

Limitations
 Thread interruption not supported by cur- Resources
rent implementations
 http://java.sun.com
{ language reference
 ThreadDeath doesn't appear to always be
caught { virtual machine reference

 ThreadGroups may be leaked


 http://www.cs.wustl.edu/schmidt/cs544/
 on our systems, /usr/bin must be ahead
of /pkg/gnu/bin in path

31 32

Anda mungkin juga menyukai