ryerson university cps8304 1 distributing computing with java

33
Ryerson University CPS8304 1 Distributing Computing with Java

Upload: horatio-bryan

Post on 11-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 1

Distributing Computing with Java

Page 2: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 2

Topics PROGRAMMING ENVIRONMENT URLs MULTITHREADING MUTUAL EXCLUSION CLIENT/SERVER PROGRAMMING

Distributing Computing with Java

Page 3: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 3

Programming Environment

Java compiler (for example jdk6 for Windows) can be downloaded from http://www.java.sun.com

Java IDE Editor can be download from http://www.jcreator.com/ See these examples if you are new in java

programmingMore information for java can be found in

Java Tutorial from java.sun.com

Page 4: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 4

NETWORKING BASIC-URLs URL is an acronym for Uniform Resource Locator and is a reference

(an address) to a resource on the Internet. URL is used to represent the "location" of a webpage or web-based

application. URLs:

are strings that describe how to find a resource on the Internet represent names of resources which can be files, databases,

applications, etc.. resource names contain a host machine name, filename, port

number, and other information. may also specify a protocol identifier (e.g., http, ftp)

Here is an example of a full URL: http://www.scs.ryerson.ca/~aabhari/WN07cps801assignment1.html#URLs

http:// is the protocol identifier which indicates the protocol that will be used to obtain the resource.

the remaining part is the resource name, and its format depends on the protocol used to access it.

Distributing Computing with Java

Page 5: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 5

NETWORKING BASIC-URLs The complete list of components that can be found in a URL

resource name are as follows: Host Name

The name of the machine on which the resource lives: http://www.scs.ryerson.ca:80

/~aabhari/WN07cps801assignment1.html#URLs

Port # (optional) The port number to which to connect: http://www.scs.ryerson.ca:80

/~aabhari/WN07cps801assignment1.html#URLs

Filename The pathname to the file on the machine: http://www.scs.ryerson.ca:80

/~aabhari/WN07cps801assignment1.html#URLs

Reference (optional) A reference to a named anchor (a.k.a. target) within a resource

that usually identifies a specific location within a file: http://www.scs.ryerson.ca:80

/~aabhari/WN07cps801assignment1.html#URLs

Distributing Computing with Java

Page 6: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 6

NETWORKING BASIC-URLs In JAVA, there is a URL class defined in the java.net package. We can create our own URL objects as follows:

URL ryerson = new URL("http://www.scs.ryerson.ca/~aabhari/");

JAVA will "dissect" the given String in order to obtain information about protocol, hostName, file etc.... Due to this, JAVA may throw a MalformedURLException ... so we will need to do this:

try { URL ryerson = new URL("http://www.scs.ryerson.ca/~aabhari/");} catch(MalformedURLException e) { ... }

Another way to create a URL is to break it into its various components:

try { URL theseNotes = new URL (http://www.scs.ryerson.ca:80

/~aabhari/WN07cps801assignment1.html#URLs)} catch(MalformedURLException e) { ...}

Distributing Computing with Java

Page 7: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 7

NETWORKING BASIC-URLs If you take a look at the JAVA API, you will

notice some other constructors as well. The URL class also supplies methods for

extracting the parts (protocol, host, file, port and reference) of a URL object.

Here is an example that demonstrates what can be accessed.

Note that this example only manipulates a URL object, it does not go off to grab any webpages :) :

Distributing Computing with Java

Page 8: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 8

NETWORKING BASIC-URLsimport java.net.*; public class URLexample { public static void main(String[] args) { URL theseNotes = null; try { theseNotes = new URL("http", "www.scs.ryerson.ca", 80, "/~aabhari/WN07cps801assignment1.html"); } catch(MalformedURLException e) { e.printStackTrace(); } System.out.println(theseNotes); System.out.println("protocol = " + theseNotes.getProtocol()); System.out.println("host = " + theseNotes.getHost()); System.out.println("filename = " + theseNotes.getFile()); System.out.println("port = " + theseNotes.getPort()); System.out.println("ref = " + theseNotes.getRef()); } }

Distributing Computing with Java

Page 9: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 9

NETWORKING BASIC-URLs After creating a URL object, you can actually connect to

that webpage and read the contents of the URL by using its openStream() method which returns an InputStream.

You actually read from the webpage as if it were a simple text file.

If an attempt is made to read from a URL that does not exist, JAVA will throw an UnknownHostException.

Here is an example that reads a URL directly. It actually reads the file representing this set of notes and

displays it line by line to the console. Notice that it reads the file as a text file, so we simply get

the HTML code. Also, you must be connected to the internet to run this

code:

Distributing Computing with Java

Page 10: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 10

NETWORKING BASIC-URLsimport java.net.*; import java.io.*; public class URLReaderExample { public static void main(String[] args) { URL theseNotes = null; try { theseNotes = new URL("http", "www.scs.ryerson.ca", 80, "/~aabhari/mainpage.html"); BufferedReader in = new BufferedReader( new InputStreamReader(theseNotes.openStream())); // Now read the webpage file String lineOfWebPage; while ((lineOfWebPage = in.readLine()) != null) System.out.println(lineOfWebPage);

in.close(); // Close the connection to the net } catch(MalformedURLException e) { System.out.println("Cannot find webpage " + theseNotes); } catch(IOException e) { System.out.println("Cannot read from webpage " + theseNotes); } } }

Distributing Computing with Java

Page 11: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 11

NETWORKING BASIC-URLs Example: Here is a modification to the above example that reads

the URL by making a URLConnection first. Since the tasks of opening a connection to a webpage

and reading the contents may both generate an IOException, we cannot distinguish the kind of error that occured.

By trying to establish the connection first, if any IOExceptions occur, we know they are due to a connection problem.

Once the connection has been established, then any further IOException errors would be due to the reading of the webpage data.

Distributing Computing with Java

Page 12: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 12

NETWORKING BASIC-URLsimport java.net.*; import java.io.*; public class URLConnectionReaderExample { public static void main(String[] args) { URL theseNotes = null; BufferedReader in = null; try { theseNotes = new URL("http", "www.scs.ryerson.ca", 80, "/~aabhari/mainpage.html"); } catch(MalformedURLException e) { System.out.println("Cannot find webpage " + theseNotes); System.exit(-1); } try { URLConnection aConnection = theseNotes.openConnection(); in = new BufferedReader( new InputStreamReader( aConnection.getInputStream())); } catch(IOException e) { System.out.println("Cannot connect to webpage " + theseNotes); System.exit(-1); } try { // Now read the webpage file String lineOfWebPage; while ((lineOfWebPage = in.readLine()) != null) System.out.println(lineOfWebPage); in.close(); // Close the connection to the net } catch(IOException e) { System.out.println("Cannot read from webpage " + theseNotes); } } }

Distributing Computing with Java

Page 13: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 13

Multithreading A thread is sometimes called a lightweight

process, is a basic unit of processor utilization. Concurrency among processes can be exploited

because threads in different processes may be executed concurrently.

Multiple threads in the same processes can be assigned to different processors.

Threads can be used to send and receive messages while other operations within a task continues.

Java has multithreading built into the language.

Distributing Computing with Java

Page 14: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 14

Creating threads The class thread is one of the classes in

the standard Java libraries for concurrent programming.

The class support a number of methods Start spawns a new thread of control. This can be stopped or suspended by

calling the methods stop or suspend respectively.

There is also the method run to restart a thread and make it active.

Distributing Computing with Java

Page 15: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 15

Creating threads To create a new thread and execution,

one does the following: Declare a new class as a subclass of

Thread. Then override the run() method with the

code that is to be executed within the thread.

Class myThread extends thread { Public void run() { /* code to execute within thread*/ } }

Distributing Computing with Java

Page 16: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 16

Creating threads Create an instance of the Thread subclass

and make a call to the start method.

MyThread worker = new MyThread();worker.start();

Distributing Computing with Java

Page 17: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 17

Creating threads The start() method will create a thread and

execute the run() method. A thread dies when its run() method

returns or when a stop() method is called.

Distributing Computing with Java

Page 18: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 18

Creating threads Example with Hello World

Consider writing a multithreaded version of hello world.

We would print “Hello World from Thread i”, where i={1,2,3} times.

Distributing Computing with Java

Page 19: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 19

Creating threadsClass HelloWorld extends Thread { int myId; // a thread id int count; // how many times int sleepTime; //how long to pause

HelloWorld (int id, int cnt, int slp) { myid = id; count = cnt; sleepTime = slp; } public void run() { while (count -- >0) { System.out.println (‘Hello World from Thread’ +id) try{ Thread.sleep(sleepTime); } catch (Exeption e) { return; } } }Public static void main (String[] args) { new HellowWorld(1,3,100).start(); new HellowWorld(2,3,100).start();}}

Distributing Computing with Java

Page 20: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 20

The Runnable Interface Another method for running a thread is by

the Runnable interface, which provide a common protocol for objects that wish to execute code after being started.

A class that implements Runnable can run without subclasses Thread by instantiating a Thread instance and passing itself as an argument.

In this way an object that implements Runnable interface can be in a Thread.

Distributing Computing with Java

Page 21: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 21

The Runnable Interface Creating a Thread of execution using

Runnable is as follows: Declare a class that implements Runnable

and then override the run() method with the code that must be executed in the thread.

Class MyThread implements Runnable { public void run() { /* insert code to be executed here*/ }}

Distributing Computing with Java

Page 22: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 22

The Runnable Interface Create an object of the Thread subclass

and call start() method, with the created object passed as an argument.

MyThread worker = new MyThread();

new Thread(worker).start;

Distributing Computing with Java

Page 23: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 23

Mutual Exclusion In concurrent environments, it is necessary to

protect shared data from simultaneous access, which may cause problems.

In Java, mutual exclusion can be guaranteed by declaring methods as synchronized.

If a thread invokes a synchronized method on an object, the object is locked. Another thread invoking a synchronized method on the same object will be blocked until the lock is released.

Distributing Computing with Java

Page 24: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 24

Mutual Exclusion A method can be declared synchronized as follows:

Public class SynchronizedUpdate { int nSeats; public synchronize void update() { } public synchronized void howmany() { return nSeats; }}

Java allows an object to be locked without having to invoke synchronize method. The general form of this type of synchronization is as follows:

Synchronized (<object-to-lock>) statement;

Distributing Computing with Java

Page 25: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 25

Thread Scheduling Whenever multiple threads run on a single processor,

active threads take turn to execute on a single processor.

Only one thread can run on the processor at any given time. The rest wait in queue.

To force threads to execute out of their normal sequence, Java allows changing of the threads priority.

Imagine a scheduler controls the assignment of threads to processors and this uses priority to decide which tread to run on a processor.

The Java scheduler picks one of the threads with the highest priority and runs it.

Distributing Computing with Java

Page 26: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 26

Thread Scheduling Higher priority threads can always interrupt others,

lower-priority threads, even before their time slices expire.

Priority are numbers between MIN_PRIORITY and MAX_PRIORITY.

The default priority assigned is NORM_PRIORITY. The method setPriority() is used to change the priority of

a thread. For example, worker.setPriority(Thread.MIN_PRIORITY);

Worker.start();

The priority of a thread can be obtained by the method getPriority().

Distributing Computing with Java

Page 27: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 27

Thread Scheduling

Other methods of Thread class for controlling scheduling include:

Method Meaning

Stop() Kills a thread

Interrupt() Causes any kind of wait or abort

Resume() Resumes a suspended thread

Suspend() Halts a thread until resume() is called

Sleep() Causes a thread to suspend and automatically resume in a control manner

Join() Suspends the caller until the indicated thread competes

Wait() Is defined in the class object and inherited by all classes.

Causes a thread to suspend until a later notify() or notifyall() is made from another method of the object invoking wait()

Distributing Computing with Java

Page 28: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 28

Client/Server Programming The Java language provides the

constructs for building client/server distributed applications.

A server executes queries on behalf of clients and sends each client their respective results.

Each client’s request triggers a creation of a new thread in the server.

Distributing Computing with Java

Page 29: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 29

Sockets Java supports sockets that provides the capability to an

application running on one machine to connect to another different machine.

A socket abstraction consists of the data structure holding the information needed for communication, and the system calls manipulating the socket structure.

Once a socket is created, it can be used to wait for an incoming connection (passive socket), or it can be used to initiate a connection (active socket).

Java provides Socket and ServerSocket classes as an abstraction for socket programming.

Distributing Computing with Java

Page 30: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 30

Sockets The socket class provides a client-side interface. A client can establish an active connection to a remote

server by creating an instance of a socket.

Socket <connection> = new Socket (<hostname>, <portname>);

The ServerSocket class provides a server-side socket interface.

To establish a server connection and bind it to a particular port number, an instance of a ServerSocket is created.

Serversocket <connection> = new ServerSocket (<portnumber>);

Distributing Computing with Java

Page 31: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 31

Input and Output Stream Once connection is established, the client

and server can read from and write to the socket using input and output streams.

Input and output in Java are done through streams.

For example the DataInputStream and DataOutputStream are classes that provide implementations for methods to transmit Java primitive types across a stream.

Distributing Computing with Java

Page 32: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 32

Input and Output Stream The following table summarizes the read and

write methods for this two classes.

Read Write Type

readBoolean writeBoolean Boolean

readChar writeChar Char

readByte writeByte Byte

readShort writeShort Short

readInt writeInt Int

readLong writeLong Long

readFloat writeFloat Float

readDouble writeDouble Double

Distributing Computing with Java

Page 33: Ryerson University CPS8304 1 Distributing Computing with Java

Ryerson University CPS8304 33

Input and Output Stream Input and output streams can be used to

read from and write to a socket connection

DataInputStream in = new DataInputStream(<connection>.getInputStream());

DataOutputStream out = new DataOutputStream(<connection>.getoutputstream());

Distributing Computing with Java