Info 408 Distributed Applications Programming Exercise sheet nb. 4

Similar documents
INFO Ass 4. Exercise 1

Java Threads. COMP 585 Noteset #2 1

Java Threads. Written by John Bell for CS 342, Spring 2018

CS11 Java. Fall Lecture 7

OS06: Monitors in Java

Threads and Parallelism in Java

Info 408 Distributed Applications programming 2 nd semester of 2017/2018 Credits: 5 Lecturer: Dr. Antoun Yaacoub

CMSC 330: Organization of Programming Languages

Principles of Software Construction: Concurrency, Part 2

Java Threads. Introduction to Java Threads

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Threads Chate Patanothai

Multiple Inheritance. Computer object can be viewed as

Introduction to Java Threads

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Lecture 9: Introduction to Monitors

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

7. MULTITHREDED PROGRAMMING

Component-Based Software Engineering

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Concurrent Programming

Threads Questions Important Questions

Concurrent Programming using Threads

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004

Multithreaded Programming

Programming Language Concepts: Lecture 11

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Java s Implementation of Concurrency, and how to use it in our applications.

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

public class Shared0 { private static int x = 0, y = 0;

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Java Threads and intrinsic locks

Performance Throughput Utilization of system resources

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CMSC 132: Object-Oriented Programming II. Threads in Java

Contents. 6-1 Copyright (c) N. Afshartous

UNIT V CONCURRENT PROGRAMMING

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Object Oriented Programming. Week 10 Part 1 Threads

Only one thread can own a specific monitor

CS193k, Stanford Handout #8. Threads 3

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Module - 4 Multi-Threaded Programming

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

Chapter 32 Multithreading and Parallel Programming

CS211 Lecture: Concurrency, Threads; UML Activity Diagrams last revised October 11, 2007 Objectives

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Concurrency in Java Prof. Stephen A. Edwards

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

CST242 Concurrency Page 1

Interprocess Communication By: Kaushik Vaghani

Synchronized Methods of Old Versions of Java

Threads and Java Memory Model

What is a thread anyway?

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Models of concurrency & synchronization algorithms

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Animation Part 2: MoveableShape interface & Multithreading

MCS-378 Intraterm Exam 1 Serial #:

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Programming with the Service Control Engine Subscriber Application Programming Interface

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

Synchronization in Concurrent Programming. Amit Gupta

Concurrency COMS W4115. Prof. Stephen A. Edwards Spring 2002 Columbia University Department of Computer Science

Implementing Coroutines. Faking Coroutines in Java

The Java Programming Language Basics. Identifiers, Keywords, and Types. Object-Oriented Programming. Objects and Classes. Exception Handling

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

CS342: Software Design. November 21, 2017

Name of subject: JAVA PROGRAMMING Subject code: Semester: V ASSIGNMENT 1

1 interface TemperatureSensor extends java.rmi.remote 2 { 3 public double gettemperature() throws java.rmi.remoteexception; 4 public void

Chapter 19 Multithreading

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Advanced Concepts of Programming

Two Types of Semaphores

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

Shared-Memory and Multithread Programming

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

The New Java Technology Memory Model

Concurrent, Real-Time and Distributed Programming in Java

Process Management And Synchronization

Lecture 8: September 30

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

Programming with the Service Control Engine Subscriber Application Programming Interface

Monitors & Condition Synchronization

Definition: A thread is a single sequential flow of control within a program.

Synchronization COMPSCI 386

Exercise Session Week 8

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Synchronization SPL/2010 SPL/20 1

Transcription:

Lebanese University Info 408 Faculty of Science 2017-2018 Section I 1 Custom Connections Info 408 Distributed Applications Programming Exercise sheet nb. 4 When accessing a server represented by an RMI object identified by a name in the registry, the connection obtained ignores the identity of the client. When there s a need to customize services, we must configure a way to identify the client. It is not the case to provide a high level of security, but simply to facilitate the programming of the client and the server programs by allowing custom connections. To illustrate this problem, we propose a simple model in which the server displays (server-side only) the message received from the customer and by prefixing the message with the identity of the client (eg his username). 1.1 Solution by ID Exercise 1 The classical solution (but the less object oriented) is based on assigning a temporary ID. We consider the following interface for the server: ServerIDInterface public interface ServerIDInterface extends Remote public long login(string username, String password) throws RemoteException; public void logout(long ID) throws RemoteException; public void postmessage(long ID, String message) throws RemoteException; The principle is very simple: when a client wants to connect, he gets a remote reference to an implementation of ServerIDInterface through the registry. Then, he calls the login method to obtain a temporary identifier, represented by a long. If the login is not possible, the method throws eventually an exception. Once the client is connected, all the interactions with the server are done using the temporary identifier, especially the method postmessage that displays the message on the server. The logout method invalidates the temporary identifier. 1. Implement the class UserInfo that will be used by the server to represent a logged in user. The class should include the name of the user, the temporary identifier associated to the user and the subscription date of this identifier (to manage the timeout). 2. Implement the server by respecting the following guidelines: Identifiers must be unique (two connected users can not have the same identifier); It should be easy to associate an identifier to a user; The server must verify the age of the connection before allowing an action by the client. The server should implement a local method to add registered users (as couples of username and password). When starting up the server, add a few users for testing. 3. Implement a command line client to test the system. The ideal is to display the obtained login identifier in order to restart several times the client without having to reconnect on each time. 1

1.2 Solution by dedicated object Exercise 2 The proposed solution in the previous exercise is not object-oriented and exposes too much technical details. A simpler solution can be obtained by creating dedicated objects. To do this, we should separate the connection from the services. Thus, we obtein two interfaces: ServerLoginInterface public interface ServerLoginInterface extends Remote public ServerInterface login(string username,string password) throws RemoteException; ServerInterface public interface ServerInterface extends Remote public void postmessage(string message) throws RemoteException; On the client-side, the new solution is used in the following way: The client gets through the registry a remote reference to an implementation of ServerLoginInterface (there is only one instance of this object). The client calls the login method which returns a remote reference to an implementation of ServerInterface. All the interactions are thus made exclusively with ServerInterface. The idea is that each call to login produces a new object implementing ServerInterface. 1. Write a class called Display to be used on the server to print the message received on the server s monitor. This class has no practical value (we could do a direct call to System.out.println), but it can simulate the development of a complex server. 2. Write an implementation of ServerInterface that preserves the identity of the client who uses it and passes through the Display class to produce its displays. 3. Write an implementation of ServerLoginInterface. As in the previous exercise, prepare some registered users for the testing. 4. Implement a command line client to test the system. Since we should retain here the reference to the remote object in order for the mechanism to work correctly, the client should make a series of interactions to actually test the server. 2 Asynchronous Communication RMI is a RPC (remote procedure call) mechanism, which by default, it s a synchronous model: the client waits for the server to send him back a response. This model works well but it is very restrictive, especially in situations where the processing on the server can be relatively long. 2.1 Solution by using threads client-side If the server does not provide means for an asynchronous call, the only solution is to go through a thread on the client. 2

2.1.1 Basic synchronization When you call the start method of a thread, it starts and the method returns the control immediately, without waiting for the end of the execution of the run method. In some circumstances, it is useful that threads can synchronize with one another. Except for very simple cases, this requires cooperation between threads; methods stop, suspend and resume of the Thread class are deprecated. The simplest primitive for synchronization is the join method. If t is a thread, the t.join() call blocks the calling thread until t ends. The join method has variants to indicate a maximum waiting time. In addition, all versions can return the InterruptedException exception that must thus be taken into account. Exercise 1 Write a Java program with two threads (in addition to the main thread) that each displays a list of integers between 1 and n, where n is the parameter of their constructor. In order to visualize the scheduling between threads, you can introduce a random pause between two displays. Display a message in the main method when both threads complete their execution. Less rudimentary synchronization requests full support by the programmer. It should for example that the run method of the thread regularly tests the value of a variable (accessible from another thread) to check whether it should continue to operate. As a first step, we will implement it using busy waiting (which is a bad idea, see the next section). Exercise 2 Modify the thread of exercise 1 to incorporate the following features: A private thread variable, active, which indicates whether the thread should run or not. This variable is initialized to true (the thread can run) by the constructor. The class provides a method to suspend the thread and another one to restart it, by changing the value of active; The run method shows always the integers between 1 and n, but by testing between each display the value of active. If active is false, the thread pauses (duration to be determined), then tests the variable again, etc... Write a program that performs a demonstration of the suspension mechanism thus obtained (with at least two threads in addition to the main thread). 2.1.2 Advanced synchronization The problem of the previous exercise tackled the use of busy waiting (the running thread waits to be awakened) that wastes resources and is a very coarse synchronization. Fortunately, Java provides a subtle and effective mechanism to avoid busy waiting. The system is based on the wait, notify and notifyall methods of the Object class. Any Java object inherits from Object and therefore has a lock used when working with multiple threads. In certain circumstances, the use of an object by a thread requires the latter to acquire the lock of the object. If the lock is already owned by another thread, the newly arrived thread is blocked (passively) until the lock owner releases it. Both situations require the acquisition of the lock: 1. a method can be declared synchronized: in this case, it is used after obtaining the lock by the calling thread. As the lock is global to the object, no other thread can call another synchronized method of the same object (other methods are normally accessible); 2. you can use the following construction: synchronized(stuff) //instructions 3

The block thus constructed can only be executed after acquiring the lock of the object designated by stuff. When a thread has a lock on an object, it can release it in a particular way by calling the wait method (of the object). The principle of this method is that the thread goes to sleep (passively) after releasing the lock. The only way to wake up the thread is while another thread is to become the owner of the lock for the object and to call the notify method (or notifyall). This method wakes up one of the threads sleeping on the object (the notifyall method wakes them all). In terms of technical details, the wait method has variants with maximum waiting time and all versions can return the InterruptedException exception. Exercise 3 Modify the thread of exercise 1 in order to replace the busy waiting by a passive waiting mechanism based on wait and notify. You should proceed as follows: Replace the busy waiting by a synchronized block in which the pause is replaced by a wait; The thread methods of control must be declared synchronized and the restart method should use notify to wake up the thread. Reuse the demonstration program to test the suspension mechanism thus obtained. 2.1.3 Asynchronous RMI call To make an asynchronous RMI call client-side, it is sufficient to encapsulate the call in a thread as shown in the following exercise: Exercise 4 Write an RMI server that offers the classical echo method (it returns to the client the parameter of the call), but with a significant pause at the beginning of the method in order to simulate a complex calculation (you can randomize the length of the pause). Write a client program that performs the call asynchronously as follows: Write a Thread object (or Runnable) that performs the call and displays the result; Start the call in the main thread and run in parallel (still in the main principal thread) any operations (such as some displays interspersed with pauses). The problem with this exercise is that, it is the thread that executes the call that decides to display the result. In some situations, this is not really acceptable, hence the following exercise: Exercise 5 Modify the object asynchronous call of the previous exercise to get the following features: The run method should no longer display the result but simply store it in an adapted variable ; The object is to provide a method to know if the calculation is complete; The object is to provide a blocking method that returns the result of the call (blocking will be based on the couple wait/notify). Provide a demonstration of the features of this new asynchronous call. 4

2.2 Solution by pulling If the server provides services for asynchronous calls, the client programming is simplified. We start the server part by an API of type pulling: the client initiates an operation on the server, and then periodically asks the server if the operation is completed. The client is active and generally perform an busy waiting, as in the following exercise: Exercise 6 We consider the following remote interface: PullServerInterface public interface PullServerInterface extends Remote public DoSomethingResultInterface dosomething(string param) throws RemoteException; The dosomething method is asynchronous, that is to say, it must run a server-side calculation (using a thread) and returning the command as quickly as possible to the client. In order for the client to get the result of the operation, the method returns a reference to a remote object DoSomethingResultInterface. Here is the interface in question: DoSomethingResultInterface public interface DoSomethingResultInterface extends Remote public boolean isdone() throws RemoteException; public String getresult() throws RemoteException; The IsDone method returns true if and only if the server has completed the calculations for the operation. The getresult method returns the result of the operation (null if it is not completed). 1. implement DoSomethingResultInterface by a class that implements also the Runnable interface (and which extends UnicastRemoteObject): the idea is to have the code to be run (the run method) with the storage mechanism (for the isdone and getresult methods) and the RMI server (due to UnicastRemoteObject). For calculations of dosomething, we will merely do an echo with a random delay between each response. 2. Implement PullServerInterface. 3. Implement a client using PullServerInterface to establish an asynchronous call with an busy waiting. We can also provide a solution with passive waiting: Exercise 7 Repeat the previous exercise by adding to the interface DoSomethingResultInterface the following method: public void waitforresult() throws RemoteException; This method allows the client to avoid busy waiting: it blocks the client until the result is available. Implement this new version using the wait/notify couple to implement the blocking feature on the server. 5

2.3 Solution by callback (push) In some situations, the asynchronous aspect should be taken to the extreme in the sense that the time that can elapse between a method call and obtaining a response is not bounded. In fact, it is more a subscription mechanism then a call for a remote method. The typical used solution is the push: the client registers with the server and this latter calls the customer to inform him of the availability of the result. We can also imagine multiple results arriving sequentially. With RMI, a push mechanism is easy to implement. To do this, the client should create a server object (callback) that is transmitted (as remote reference) to the server when registering. When the server wishes to prevent the client, it calls a remote method of the callback object. Let us start with a simple implementation: Exercise 8 Consider the following remote interface: PushServerInterface public interface PushServerInterface extends Remote public void dosomething(string param, DoSomethingCallbackInterface callback) throws RemoteException; The dosomething method is asynchronous: it starts the server-side calculation and returns control as soon as possible. The remote reference DoSomethingCallbackInterface corresponds to an object created at the client-side that the server will use to inform the client of the calculation completion. The interface is very simple: DoSomethingCallbackInterface public interface DoSomethingCallbackInterface extends Remote public void reportcompletion(string result) throws RemoteException; 1. Implement PushServerInterface: the operation is a simple echo with random a delay response. 2. implement DoSomethingCallbackInterface with the simplest possible way, for example by making a display (on the client) using the reportcompletion method. 3. Implement a client to test the mechanism. We can settle for something very simple using the fact that JVM stops only if the proposed remote objects are not used (through the mechanism of distributed garbage collector). 4. Test the behavior of the server when the client ends without waiting for the completion of the call. What is wrong in the previous exercise is that no synchronization is implemented at the client-side. For something more realistic, it should be that the object implementing DoSomethingCallbackInterface get inspired by the mechanisms presented earlier to enable such synchronization: Exercise 9 Add to the implementation of DoSomethingCallbackInterface written in the previous exercise, methods inspired from exercises 6 and 7 allowing the client to wait actively and / or passively the server calls. Modify the test program to perform a demonstration of the new features. 6