Distributing%20Computing%20with%20Java - PowerPoint PPT Presentation

About This Presentation
Title:

Distributing%20Computing%20with%20Java

Description:

Distributing Computing with Java. Ryerson University CPS8304. 2 ... Distributing Computing with Java. Ryerson University CPS8304. 3. Programming Environment ... – PowerPoint PPT presentation

Number of Views:18
Avg rating:3.0/5.0
Slides: 34
Provided by: Abdy
Category:

less

Transcript and Presenter's Notes

Title: Distributing%20Computing%20with%20Java


1

Distributing Computing with Java
2
Topics
Distributing Computing with Java
PROGRAMMING ENVIRONMENT URLs MULTITHREADING MUTUAL EXCLUSION CLIENT/SERVER PROGRAMMING
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
    programming
  • More information for java can be found in Java
    Tutorial from java.sun.com

4
NETWORKING BASIC-URLs
Distributing Computing with Java
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.htmlURLs 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.
5
NETWORKING BASIC-URLs
Distributing Computing with Java
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.ca80 /aabhari/WN07cps801assignment1.htmlURLs Port (optional) The port number to which to connect http//www.scs.ryerson.ca80 /aabhari/WN07cps801assignment1.htmlURLs Filename The pathname to the file on the machine http//www.scs.ryerson.ca80 /aabhari/WN07cps801assignment1.htmlURLs 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.ca80 /aabhari/WN07cps801assignment1.htmlURLs
6
NETWORKING BASIC-URLs
Distributing Computing with Java
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.ca80 /aabhari/WN07cps801assignment1.htmlURLs) catch(MalformedURLException e) ...
7
NETWORKING BASIC-URLs
Distributing Computing with Java
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 )
8
NETWORKING BASIC-URLs
Distributing Computing with Java
import 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())
9
NETWORKING BASIC-URLs
Distributing Computing with Java
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
10
NETWORKING BASIC-URLs
Distributing Computing with Java
import 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)
11
NETWORKING BASIC-URLs
Distributing Computing with Java
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.
12
NETWORKING BASIC-URLs
Distributing Computing with Java
import 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)
13
Multithreading
Distributing Computing with Java
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.
14
Creating threads
Distributing Computing with Java
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.
15
Creating threads
Distributing Computing with Java
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/
16
Creating threads
Distributing Computing with Java
Create an instance of the Thread subclass and make a call to the start method. MyThread worker new MyThread() worker.start()
17
Creating threads
Distributing Computing with Java
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.
18
Creating threads
Distributing Computing with Java
Example with Hello World Consider writing a multithreaded version of hello world. We would print Hello World from Thread i, where i1,2,3 times.
19
Creating threads
Distributing Computing with Java
Class 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 -- gt0) 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()
20
The Runnable Interface
Distributing Computing with Java
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.
21
The Runnable Interface
Distributing Computing with Java
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/
22
The Runnable Interface
Distributing Computing with Java
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
23
Mutual Exclusion
Distributing Computing with Java
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.
24
Mutual Exclusion
Distributing Computing with Java
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 (ltobject-to-lockgt) statement
25
Thread Scheduling
Distributing Computing with Java
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.
26
Thread Scheduling
Distributing Computing with Java
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().
27
Thread Scheduling
Distributing Computing with Java
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()
28
Client/Server Programming
Distributing Computing with Java
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 clients request triggers a creation of a new thread in the server.
29
Sockets
Distributing Computing with Java
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.
30
Sockets
Distributing Computing with Java
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 ltconnectiongt new Socket (lthostnamegt, ltportnamegt) 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 ltconnectiongt new ServerSocket (ltportnumbergt)
31
Input and Output Stream
Distributing Computing with Java
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.
32
Input and Output Stream
Distributing Computing with Java
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
33
Input and Output Stream
Distributing Computing with Java
Input and output streams can be used to read from and write to a socket connection DataInputStream in new DataInputStream(ltconnectiongt.getInputStream()) DataOutputStream out new DataOutputStream(ltconnectiongt.getoutputstream())
Write a Comment
User Comments (0)
About PowerShow.com