Course Topic 1
Reading Material
Java History
Run-time Compilation
Prerequisites
Pointers in Java?
We say:
x is an or instance variable, or non-static field.
foo() is an instance method, or non-static method.
y is a static field, or class variable.
goo() is a static method, or class method.
Class Loading
The CLASSPATH
The class path is a colon-separated (semicolonseparated in Windows) list of directories and jar
files.
If the class path is empty, it is equivalent to .. But if
the class path is not empty, . is not included by default.
A directory entry means a root directory in which class
files or package directories are stored; a jar entry means
a jar archive in which class files or package directories
are stored.
Binary Compatibility
There is a useful property called binarycompatibility between classes. This means that
(within some specified limits) two class files that
implement the same public interface can be used
interchangeably.
It also means that if you pick up an inappropriate
implementation of a given class from the CLASSPATH
at runtime, things can go wrong in an opaque way.
Notice the method add() has the modifier native, and the
body of the method declaration is missing
It is replaced by a semicolonsimilar to abstract methods in
interfaces, etc. But in this case the method isnt abstract.
The implementation of a native method will be given in another
language, typically C or C++ (we consider C).
A Definition of Java_B_add()
JNIEXPORT jlong JNICALL Java_B_add(JNIEnv * env,
jobject this, jintArray nums) {
jint *cnums ;
int i, n ;
jlong sum = 0 ;
n = (*env)->GetArrayLen(env, nums) ;
cnums = (*env)->GetIntArrayElements(env, nums, NULL) ;
1.
2.
3.
Other Java techniques (e.g. Java for XML, Web Services) will be
introduced as the course unfolds.
1) Multithreaded
Programming in Java
24
+ Partial failures
Concurrent
programming
Distributed
programming
Suggested Exercises
29
Threads of Execution
There are two ways to create a thread instance (and define the
thread run() method). Choose at your convenience:
1. Extend the Thread class and override the run() method, e.g.:
class MyThread extends Thread {
public void run() {
System.out.println(Hello from another thread) ;
}
}
...
Thread thread = new MyThread() ;
}
...
Thread thread = new MyThread(new MyRunnable()) ;
Starting a Thread
}
...
Thread [] threads = new Thread [p] ;
for(int i = 0 ; i < p ; i++)
threads [i] = new MyThread(i) ;
for(int i = 0 ; i < p ; i++)
threads [i].start() ;
Remarks
Mutual Exclusion
37
Avoiding Interference
In POSIX threads, for example, the lock objects are called mutexes.
Monitors
Every Java object is created with its own lock (and every lock is
associated with an objectthere is no way to create an isolated
mutex). In Java this lock is often called the monitor lock.
Thread B
call to counter.increment()
// body of synchronized method
tmp1 = count ;
count = tmp1 + 1 ;
counter.increment() returns
call to counter.decrement()
Blocked
// body of synchronized method
tmp2 = count ;
count = tmp2 - 1 ;
counter.decrement() returns
Caveats
Remarks
The Node class just has a data field (type Object) and a
next field (type Node).
The following slide gives an example of what could go
wrong without mutual exclusion. It assumes two
threads concurrently add nodes to the queue.
In the initial state, Z is the last item in the queue. In the final
state, the X node is orphaned, and the back pointer is null.
null
back
Thread B: add(Y)
null
back
null
null
back
back = back.next ;
X
Z
null
back = back.next ;
null
back
X
Z
back
null
null
null
Deadlock
synchronized(y) {
}
}
Thread B
synchronized(y) {
synchronized(x) {
}
}
General Synchronization
48
A Motivating Example
Busy Waiting
while(true) {
Object result = rem() ;
if (result != null)
return result ;
}
A Simplified Example
public class Semaphore {
int s ;
public Semaphore(int s) { this.s = s ; }
public synchronized void add() {
s++ ;
notify() ;
}
Remarks I
Remarks II
Remarks III
Another Example
public class Barrier {
private int n, generation = 0, count = 0 ;
public Barrier(int n) { this.n = n ; }
public synchronized void synch() throws InterruptedException {
int genNum = generation ;
count++ ;
if(count == n) {
count = 0 ;
generation++ ;
notifyAll() ;
}
else
while(generation == genNum)
wait() ;
}
}
Remarks
61
Other Features
Join Operations
Sleeping
Interrupting Threads
Thread Groups
Thread-Local Variables
Volatile Variables
the JVM is supposed to synchronize the value of any threadlocal (cached) copy of the variable with central storagemaking
it visible to all threadsevery time the variable is updated.
The exact semantics of volatile variables and the Java memory
model in general is still controversial, see for example:
A New Approach to the Semantics of Multithreaded Java,
Jeremy Manson and William Pugh,
http://www.cs.umd.edu/~pugh/java/memoryModel/
2) Network
Programming in Java
72
Sockets background
Socket classes, with simple HTTP examples
Internet address classes
URL classes
JSSE elements
74
Sockets
Client
socket() : create
socket
connect():
write()
: send request
Server
read()
: get reply
Port Numbers
Making a Connection
Sockets in Java
A Simple Client
import java.io.* ;
import java.net.* ;
public class TrivialBrowser {
public static void main(String [] args) throws IOException {
Socket s = new Socket(www.grid2004.org, 80) ;
PrintWriter out = new PrintWriter(
new OutputStreamWriter(s.getOutputStream())) ;
out.print("GET /spring2004/index.html HTTP/1.1\r\n") ;
out.print("Host: www.grid2004.org\r\n\r\n") ;
out.flush() ;
Remarks
Cut and paste this slide, compile and run the code. It
prints out the HTML source for the course home page.
It connects to port 80 on the server (the HTTP port).
It gets an output stream to write to the socket using
getOuputStream().
It sends an HTTP GET request on the stream, specifying
the file it1spring01/index.html relative to the servers
document root.
It gets an input stream to read from the socket using
getInputStream().
It copies lines from the socket connection to the console.
A Simple Server
public static void main(String [] args) throws Exception {
ServerSocket server = new ServerSocket(8080) ;
while(true) {
Socket sock = server.accept() ;
BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()) ;
String header = in.readLine() ;
. . . Skip over any other lines in request packet . . .
String fileName = pathcomponentfrom2ndfieldof header ;
DataOutputStream out =
new DataOutputStream(sock.getOutputStream()) ;
if( filefileNameexists ) {
byte [] bytes = contentsoflocalfile fileName ;
out.writeBytes(HTTP/1.0 200 OK\r\n) ;
out.writeBytes(Content-Length: + bytes.length + \r\n) ;
out.writeBytes(Content-Type: text/html\r\n\r\n) ;
out.write(bytes) ;
} else { SendHTTPerrorstatus }
}
}
Remarks
Notable things you cant do include I/O in nonblocking mode, and any kind of select functionality.
These important features werent added until J2SE 1.4, in
the java.nio packages.
In unaugmented java.net sockets, the closest you can come is
to execute socket operations in dedicated threads.
Internet Addresses
Example methods
static InetAddress getByName(String host) {}
static InetAddress getByAddress(byte [] addr) {}
byte [] getAddress {}
String getCanonicalHostName() {}
static InetAddress getLocalHost() {}
InetAddress objectscanbepassedtotheconstructors
ofsocketclasses.
URL Objects
UDP in Java
sock.send(packet) ;
System.out.println(message) ;
94
References
98
Buffers
Buffer
CharBuffer
IntBuffer
DoubleBuffer
ShortBuffer
LongBuffer
FloatBuffer
ByteBuffer
MappedByt
eBuffer
Creating Buffers
Examples
import java.nio.* ;
public class CreateBuffers {
public static void main(String [] args) {
int BUF_SIZE = 1024 ;
byte [] myBacking = new byte [BUF_SIZE] ;
ByteBuffer buffer1 = ByteBuffer.wrap(myBacking) ;
// Uses array myBacking for storage.
ByteBuffer buffer2 = ByteBuffer.allocate(BUF_SIZE) ;
// Uses buffer2.array() for storage.
ByteBuffer buffer3 = ByteBuffer.allocateDirect(BUF_SIZE) ;
// Uses inaccessible system memory for storage.
}
put(byte b)
put(byte [] src)
The put() and get() operations shown above are all relative
operations: they get data from, or insert data into, the
buffer, starting at the current position in the buffer.
Remarks
You can write other primitive types (char, int, double, etc)
to a ByteBuffer by methods like:
ByteBuffer putChar(char value)
ByteBuffer putInt(int value)
Endian-ness
View Buffers
Channels
111
Channels
Channels are like high-level versions of the filedescriptors in UNIX-like operating systems.
So a channel is a handle for performing I/O operations,
etc, on an open file or socket.
FileInputStream, FileOutputStream,
RandomAccessFile, Socket,
ServerSocket or DatagramSocket.
The traditional Java handle objects are still usedthe
channel just provides extra NIO-specific functionality.
<<<interface>>>
ByteChannel
FileChannel
DatagramChannel
SelectableChannel
SocketChannel
ServerSocketChannel
Opening A Channel
Examples
import java.nio.* ;
import java.nio.* ;
import java.nio.* ;
public class CreateChannels {
public static void main(String [] args) throws IOException {
InetSocketAddress addr =
new InetSocketAddress("www.grid2004.org", 80) ;
SocketChannel sc = SocketChannel.open(addr) ;
// Create a socket channel.
RandomAccessFile raf =
new RandomAccessFile("CreateChannels.class", "r") ;
FileChannel fc = raf.getChannel() ;
// Get a file channel.
}
Using Channels
Nonblocking Operations
socket.configureBlocking(false) ;
Interruptible Operations
Selectors
122
Readiness Selection
Setting Up Selectors
Example
Here we create a selector, and register three preexisting channels to the selector:
Selector selector = Selector.open() ;
channel1.register (selector, SelectionKey.OP_READ) ;
channel2.register (selector, SelectionKey.OP_WRITE) ;
channel3.register (selector, SelectionKey.OP_READ |
SelectionKey.OP_WRITE) ;
Ready Sets
Iterator it = selector.selectedKeys().iterator() ;
while( it.hasNext() ) {
SelectionKey key = it.next() ;
if( key.isReadable() )
perform read() operation on key.channel()
if( key.isWriteable() )
perform write() operation on key.channel()
if( key.isConnectable() )
perform connect() operation on key.channel()
if( key.isAcceptable() )
perform accept() operation on key.channel()
it.remove() ;
Remarks
Key Attachments