Ryerson University CPS8304 1 Distributing Computing with Java.

Slides:



Advertisements
Similar presentations
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
Advertisements

Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
Threads ICW Lecture 10 Tom Chothia. Last Time XML JDOM XPATH.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Networking java.net package, which provides support for networking. Its creators have called Java “programming for the Internet.” Socket :- A network socket.
Multithreading.
Computer Networks  Network - A system of computers interconnected in order to share information.  Data transmission - consists of sending and receiving.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 12 Communicating over.
Import java.net.*; import java.io.*; public class LowPortScanner { public static void main(String[] args) { String host = "localhost"; if (args.length.
1 Java Threads Instructor: Mainak Chaudhuri
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Java Threads Representation and Management of Data on the Internet.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 RMI.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
© Lethbridge/Laganière 2005 Chap. 3: Basing Development on Reusable Technology The Client-Server Architecture A distributed system is a system in.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Dynamic Architectures (Component Reconfiguration) with Fractal.
Concurrent Programming and Threads Threads Blocking a User Interface.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
CS 4244: Internet Programming Network Programming in Java 1.0.
Threading and Concurrency COM379T John Murray –
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Java 3: Odds & Ends Advanced Programming Techniques.
Part 4: Network Applications Client-server interaction, example applications.
Java zJava Design Principles xSafety  Primitive data types have fixed sizes and meanings  Type safety (strongly typed)  Strict control of pointers xObject.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
URL Programming Mimi Opkins CECS277. What is a URL?  URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Distributed Systems CS Project 1: File Storage and Access Kit (FileStack) Recitation 1, Aug 29, 2013 Dania Abed Rabbou and Mohammad Hammoud.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Multithreading & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Today Threading, Cont. Multi-core processing. Java Never Ends! Winter 2016CMPE212 - Prof. McLeod1.
Threads in Java Two ways to start a thread
Multithreaded Programming in Java
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
Multithreading.
Multithreading.
Multithreaded Programming
Multithreading in java.
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Ryerson University CPS Distributing Computing with Java

Ryerson University CPS Topics  PROGRAMMING ENVIRONMENT  URLs  MULTITHREADING  MUTUAL EXCLUSION  CLIENT/SERVER PROGRAMMING Distributing Computing with Java

Ryerson University CPS Programming Environment  Java compiler (for example jdk6 for Windows) can be downloaded from  Java IDE Editor can be download from  See these examples if you are new in java programmingthese examples More information for java can be found in Java Tutorial from java.sun.com

Ryerson University CPS 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:   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

Ryerson University CPS 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:  /~aabhari/WN07cps801assignment1.html#URLs  Port # (optional)  The port number to which to connect:  /~aabhari/WN07cps801assignment1.html#URLs  Filename  The pathname to the file on the machine:  /~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:  /~aabhari/WN07cps801assignment1.html#URLs Distributing Computing with Java

Ryerson University CPS 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("  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(" } catch(MalformedURLException e) {... }  Another way to create a URL is to break it into its various components: try { URL theseNotes = new URL ( /~aabhari/WN07cps801assignment1.html#URLs) } catch(MalformedURLException e) {... } Distributing Computing with Java

Ryerson University CPS 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

Ryerson University CPS NETWORKING BASIC-URLs import java.net.*; public class URLexample { public static void main(String[] args) { URL theseNotes = null; try { theseNotes = new URL("http", " 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

Ryerson University CPS 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

Ryerson University CPS NETWORKING BASIC-URLs import java.net.*; import java.io.*; public class URLReaderExample { public static void main(String[] args) { URL theseNotes = null; try { theseNotes = new URL("http", " 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

Ryerson University CPS 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

Ryerson University CPS NETWORKING BASIC-URLs 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", " 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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS Creating threads 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 -- >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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS 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 ( ) statement; Distributing Computing with Java

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS Thread Scheduling  Other methods of Thread class for controlling scheduling include: MethodMeaning 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

Ryerson University CPS 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

Ryerson University CPS 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

Ryerson University CPS 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 = new Socket (, );  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 = new ServerSocket ( ); Distributing Computing with Java

Ryerson University CPS 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

Ryerson University CPS Input and Output Stream  The following table summarizes the read and write methods for this two classes. ReadWriteType readBooleanwriteBooleanBoolean readCharwriteCharChar readBytewriteByteByte readShortwriteShortShort readIntwriteIntInt readLongwriteLongLong readFloatwriteFloatFloat readDoublewriteDoubleDouble Distributing Computing with Java

Ryerson University CPS Input and Output Stream  Input and output streams can be used to read from and write to a socket connection DataInputStream in = new DataInputStream(.getInputStream()); DataOutputStream out = new DataOutputStream(.getoutputstream()); Distributing Computing with Java