INFO Ass 4. Exercise 1

Size: px
Start display at page:

Download "INFO Ass 4. Exercise 1"

Transcription

1 Exercise 1 INFO Ass 4 public class UserInfo public static final long TIME_OUT = 1000 * 3000 ; public String user; public long id; public long creationdate; public UserInfo(String user,long id) this.user = user; this.id = id; this.creationdate = System.currentTimeMillis(); public boolean isvalid() return (System.currentTimeMillis() - creationdate) < TIME_OUT; 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; import java.rmi.server.*; import java.util.*; public class ServerIDImpl extends UnicastRemoteObject implements ServerIDInterface private Map idmap; private Random rng; private Map passmap; public ServerIDImpl() throws RemoteException super(); idmap = new HashMap(); passmap = new HashMap(); rng = new Random(); // local method public void adduser(string username, String password) passmap.put(username,password); 1 / 22

2 public long login(string username, String password) throws RemoteException if(passmap.containskey(username)) if(passmap.get(username).equals(password)) long id; Long idobj; do id = rng.nextlong(); idobj = new Long(id); while(idmap.containskey(idobj)); idmap.put(idobj,new UserInfo(username,id)); System.out.println("Connection of " + username + " id : "+id); return id; throw new RemoteException("Connection refused"); public void logout(long id) throws RemoteException Long idobj = new Long(id); if(idmap.containskey(idobj)) idmap.remove(idobj); else throw new RemoteException("Invalid ID"); public void postmessage(long id, String message) throws RemoteException Long idobj = new Long(id); if(idmap.containskey(idobj)) UserInfo user = (UserInfo)idMap.get(idObj); if(user.isvalid()) System.out.println(user.user+" : "+message); return; else // timeout logout(id); 2 / 22

3 throw new RemoteException("Invalid ID"); ServerIDImpl server = new ServerIDImpl(); server.adduser("toto","1234"); server.adduser("titi","1234"); server.adduser("fifi","1234"); Naming.rebind("rmi:// :1234/ServerID",server); System.out.println("Server Started"); public class Client ServerIDInterface server = (ServerIDInterface)Naming.lookup("rmi:// :1234/ServerID"); if(args[0].equals("login")) System.out.println(server.login(args[1],args[2])); else if(args[0].equals("logout")) server.logout(long.parselong(args[1])); else if(args[0].equals("post")) server.postmessage(long.parselong(args[1]),args[2]); Exercise 2 public interface ServerLoginInterface extends Remote public ServerInterface login(string username, String password) throws RemoteException; import java.rmi.server.*; import java.util.*; public class ServerLoginImpl extends UnicastRemoteObject implements ServerLoginInterface private Map passmap; private Display display; public ServerLoginImpl() throws RemoteException 3 / 22

4 super(); passmap = new HashMap(); display = new Display(); // local method public void adduser(string user,string pass) passmap.put(user,pass); public ServerInterface login(string user,string pass) throws RemoteException if(passmap.containskey(user)) if(passmap.get(user).equals(pass)) System.out.println("Connection of "+user); return new ServerImpl(display,user); throw new RemoteException("Connection refused"); ServerLoginImpl server = new ServerLoginImpl(); server.adduser("toto","1234"); server.adduser("titi","1234"); server.adduser("fifi","1234"); Naming.rebind("rmi:// :1234/ServerLogin",server); System.out.println("Server Started"); public interface ServerInterface extends Remote public void postmessage(string message) throws RemoteException; import java.rmi.server.*; public class ServerImpl extends UnicastRemoteObject implements ServerInterface private Display display; private String user; public ServerImpl(Display display, String user) throws RemoteException 4 / 22

5 super(); this.display = display; this.user = user; public void postmessage(string msg) throws RemoteException display.post(user, msg); public class Display public void post(string username, String message) System.out.println(username + " : " + message); public class Client ServerLoginInterface server = (ServerLoginInterface)Naming.lookup("rmi:// :1234/ServerLogin"); ServerInterface connection1 = server.login("toto","1234"); ServerInterface connection2 = server.login("fifi","1234"); connection1.postmessage("hello World!"); connection2.postmessage("hi toto"); connection1.postmessage("where are you fifi?"); connection2.postmessage("somewhere in this World ;)"); 5 / 22

6 INFO Ass 4 Exercise 1 import java.util.random; public class Demo public static void main(string[] args) Random rng = new Random(); DisplayInteger t1 = new DisplayInteger(20,rng); DisplayInteger t2 = new DisplayInteger(15,rng); t1.start(); t2.start(); System.out.println("Launching Finished"); try t1.join(); t2.join(); catch(interruptedexception e) System.out.println(e); System.out.println("Threads Finished"); import java.util.random; public class DisplayInteger extends Thread private int max; private Random rng; public DisplayInteger(int n,random rng) max = n; this.rng = rng; public void run() String name = getname(); for(int i=1;i<=max;i++) System.out.println(name+": "+i); try sleep(math.abs(rng.nextint())%1500); catch (InterruptedException e) System.out.println(name+" terminated"); 6 / 22

7 Exercise 2 import java.util.random; public class Demo public static void main(string[] args) Random rng = new Random(); DisplayInteger t1 = new DisplayInteger(20,rng); DisplayInteger t2 = new DisplayInteger(15,rng); t1.start(); t2.start(); System.out.println("Launching Finished"); t1.suspendt(); try Thread.sleep(4000); catch (InterruptedException e) t2.suspendt(); t1.resumet(); try Thread.sleep(4000); catch (InterruptedException e) t2.resumet(); import java.util.random; public class DisplayInteger extends Thread private int max; private Random rng; private boolean active; public DisplayInteger(int n,random rng) max = n; this.rng = rng; active = true; public void run() String name = getname(); for(int i=1;i<=max;i++) while(!active) // active waiting / busy waiting System.out.println("active waiting ("+name+")"); try sleep(1000); catch (InterruptedException e) System.out.println(name+": "+i); try sleep(math.abs(rng.nextint())%1500); catch (InterruptedException e) 7 / 22

8 System.out.println(name+" terminated"); public void suspendt() active = false; System.out.println("Suspension of "+getname()); public void resumet() active = true; System.out.println("Resuming "+getname()); 8 / 22

9 Exercise 3 import java.util.random; public class Demo public static void main(string[] args) Random rng = new Random(); DisplayInteger t1 = new DisplayInteger(20,rng); DisplayInteger t2 = new DisplayInteger(15,rng); t1.start(); t2.start(); System.out.println("Launching Finished"); t1.suspendt(); try Thread.sleep(4000); catch (InterruptedException e) t2.suspendt(); t1.resumet(); try Thread.sleep(4000); catch (InterruptedException e) t2.resumet(); import java.util.random; public class DisplayInteger extends Thread private int max; private Random rng; private boolean active; public DisplayInteger(int n,random rng) max = n; this.rng = rng; active = true; public void run() String name = getname(); for(int i=1;i<=max;i++) synchronized(this) while(!active) // passive waiting System.out.println("Passive waiting ("+name+")"); try wait(); catch (InterruptedException e) 9 / 22

10 System.out.println(name+": "+i); try sleep(math.abs(rng.nextint())%1500); catch (InterruptedException e) System.out.println(name+" terminated"); public synchronized void suspendt() active = false; System.out.println("Suspension of "+getname()); public synchronized void resumet() active = true; System.out.println("Resuming "+getname()); notify(); 10 / 22

11 Exercise 4 public interface ServerInterface extends Remote public String echo(string message) throws RemoteException; import java.rmi.server.*; import java.util.*; public class ServerImpl extends UnicastRemoteObject implements ServerInterface public ServerImpl() throws RemoteException super(); public String echo(string message) throws RemoteException System.out.println("Ping"); try Thread.sleep(5000); catch(interruptedexception e) System.out.println("Pong"); return "["+message+"]"; ServerImpl server = new ServerImpl(); Naming.rebind("rmi:// :1234/ServerEcho",server); System.out.println("Server Started"); public class Client // the final is added because of the anonymouse class final ServerInterface server = (ServerInterface)Naming.lookup("rmi:// :1234/ServerEcho"); // solution with anonymouse class Thread t = new Thread(new Runnable() public void run() try System.out.println(server.echo("Hello World!")); catch(remoteexception e) System.out.println(e); ); t.start(); 11 / 22

12 System.out.println("Starting the call"); for(int i=1;i<=5;i++) System.out.println(i); try Thread.sleep(1500); catch (InterruptedException e) System.out.println("End of main"); 12 / 22

13 Exercise 5 public class AsynchronousCall extends Thread private ServerInterface server; private boolean done; private String result; private String param; public AsynchronousCall(ServerInterface server,string param) this.server = server; done = false; this.param = param; public void run() try result = server.echo(param); catch(remoteexception e) System.out.println(e); synchronized(this) done = true; notify(); public synchronized boolean isdone() return done; public synchronized String getresult() while(!done) try wait(); catch (InterruptedException e) return result; public class Client ServerInterface server = (ServerInterface)Naming.lookup("rmi:// :1234/ServerEcho"); AsynchronousCall call = new AsynchronousCall(server,"Hello World!"); call.start(); 13 / 22

14 System.out.println("Starting the call"); for(int i=1;i<=5;i++) System.out.println(i); try Thread.sleep(1500); catch (InterruptedException e) System.out.println("Waiting the result"); System.out.println(call.getResult()); System.out.println("End of main"); 14 / 22

15 Exercise 6 public interface PullServerInterface extends Remote public DoSomethingResultInterface dosomething(string param) throws RemoteException; import java.rmi.server.*; public class PullServerImpl extends UnicastRemoteObject implements PullServerInterface public PullServerImpl() throws RemoteException super(); public DoSomethingResultInterface dosomething(string param) throws RemoteException System.out.println("Ping"); DoSomethingResultImpl result = new DoSomethingResultImpl(param); Thread support = new Thread(result); support.start(); System.out.println("Pong"); return result; PullServerImpl server = new PullServerImpl(); Naming.rebind("rmi:// :1234/ServerPull",server); System.out.println("Server Started"); public interface DoSomethingResultInterface extends Remote public boolean isdone() throws RemoteException; public String getresult() throws RemoteException; import java.rmi.server.*; public class DoSomethingResultImpl extends UnicastRemoteObject implements DoSomethingResultInterface,Runnable private String param; private String result; private boolean done; public DoSomethingResultImpl(String param) throws RemoteException super(); this.param = param; done = false; public boolean isdone() throws RemoteException 15 / 22

16 System.out.println("isDone"); return done; public String getresult() throws RemoteException System.out.println("getResult"); return result; public void run() try Thread.sleep(5000); catch(interruptedexception e) result = "["+param+"]"; done = true; public class Client PullServerInterface server = (PullServerInterface)Naming.lookup("rmi:// :1234/ServerPull"); System.out.println("Starting the call"); DoSomethingResultInterface result = server.dosomething("hello World!"); boolean first = true; for(int i=1;i<=5;i++) System.out.println(i); try Thread.sleep(1500); catch (InterruptedException e) System.out.println("Waiting the result"); if(first && result.isdone()) System.out.print("Here it is : "); System.out.println(result.getResult()); first = false; System.out.println("End of main"); 16 / 22

17 Exercise 7 public interface DoSomethingResultInterface extends Remote public boolean isdone() throws RemoteException; public String getresult() throws RemoteException; public void waitforresult() throws RemoteException; import java.rmi.server.*; public class DoSomethingResultImpl extends UnicastRemoteObject implements DoSomethingResultInterface,Runnable private String param; private String result; private boolean done; public DoSomethingResultImpl(String param) throws RemoteException super(); this.param = param; done = false; public synchronized boolean isdone() throws RemoteException System.out.println("isDone"); return done; public synchronized String getresult() throws RemoteException System.out.println("getResult"); return result; public synchronized void waitforresult() throws RemoteException System.out.println("waitForResult"); while(!done) try wait(); catch(interruptedexception e) public void run() try Thread.sleep(5000); catch(interruptedexception e) synchronized(this) result = "["+param+"]"; done = true; notify(); 17 / 22

18 public class Client PullServerInterface server = (PullServerInterface)Naming.lookup("rmi:// :1234/ServerPull"); System.out.println("Starting the call"); DoSomethingResultInterface result = server.dosomething("hello World!"); boolean first = true; for(int i=1;i<=5;i++) System.out.println(i); try Thread.sleep(500); catch (InterruptedException e) System.out.println("Waiting the result"); if(first && result.isdone()) System.out.print("Here it is : "); System.out.println(result.getResult()); first = false; if(first) System.out.println("Still no result, switching to passive waiting... "); result.waitforresult(); System.out.print("Here it is : "); System.out.println(result.getResult()); System.out.println("End of main"); 18 / 22

19 Exercise 8 public interface PushServerInterface extends Remote public void dosomething(string param, DoSomethingCallbackInterface callback) throws RemoteException; import java.rmi.server.*; public class PushServerImpl extends UnicastRemoteObject implements PushServerInterface public PushServerImpl() throws RemoteException super(); public void dosomething(string param, DoSomethingCallbackInterface callback) throws RemoteException System.out.println("Ping"); DoSomething support = new DoSomething(param,callback); support.start(); System.out.println("Pong"); PushServerImpl server = new PushServerImpl(); Naming.rebind("rmi:// :1234/ServerPush",server); System.out.println("Server Started"); public class DoSomething extends Thread private String param; private DoSomethingCallbackInterface callback; public DoSomething(String param,dosomethingcallbackinterface callback) this.param = param; this.callback = callback; public void run() try Thread.sleep(5000); catch(interruptedexception e) try callback.reportcompletion(param); catch(remoteexception e) System.err.println("Cannot report completion: "+e); 19 / 22

20 public interface DoSomethingCallbackInterface extends Remote public void reportcompletion(string result) throws RemoteException; import java.rmi.server.*; public class DoSomethingCallbackImpl extends UnicastRemoteObject implements DoSomethingCallbackInterface public DoSomethingCallbackImpl() throws RemoteException super(); public void reportcompletion(string result) throws RemoteException System.out.println(result); public class Client DoSomethingCallbackImpl callback = new DoSomethingCallbackImpl(); PushServerInterface server = (PushServerInterface)Naming.lookup("rmi:// :1234/ServerPush"); System.out.println("Starting the call"); server.dosomething("hello World! ",callback); for(int i=1;i<=5;i++) System.out.println(i); try Thread.sleep(1500); catch (InterruptedException e) System.out.println("End of main"); 20 / 22

21 Exercise 9 import java.rmi.server.*; public class DoSomethingCallbackImpl extends UnicastRemoteObject implements DoSomethingCallbackInterface private String result; private boolean done; public DoSomethingCallbackImpl() throws RemoteException super(); done = false; public synchronized void reportcompletion(string result) throws RemoteException System.out.println("reportCompletion"); done = true; this.result = result; notify(); public synchronized boolean isdone() return done; public synchronized String getresult() return result; public synchronized void waitforresult() while(!done) try wait(); catch(interruptedexception e) public class Client DoSomethingCallbackImpl callback = new DoSomethingCallbackImpl(); PushServerInterface server = (PushServerInterface)Naming.lookup("rmi:// :1234/ServerPush"); System.out.println("Starting the call"); 21 / 22

22 server.dosomething("hellow World!",callback); boolean first = true; for(int i=1;i<=5;i++) System.out.println(i); try Thread.sleep(500); catch (InterruptedException e) System.out.println("Waiting for the result"); if(first && callback.isdone()) System.out.print("Here it is : "); System.out.println(callback.getResult()); first = false; if(first) System.out.println("Still no result, switching to passive waiting... "); callback.waitforresult(); System.out.print("Here it is : "); System.out.println(callback.getResult()); System.out.println("End of main"); 22 / 22

Info 408 Distributed Applications Programming Exercise sheet nb. 4

Info 408 Distributed Applications Programming Exercise sheet nb. 4 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

More information

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

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

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

Part IV Other Systems: I Java Threads

Part IV Other Systems: I Java Threads Part IV Other Systems: I Java Threads Spring 2019 C is quirky, flawed, and an enormous success. 1 Dennis M. Ritchie Java Threads: 1/6 Java has two ways to create threads: Create a new class derived from

More information

Module - 4 Multi-Threaded Programming

Module - 4 Multi-Threaded Programming Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is

More information

Unit - IV Multi-Threading

Unit - IV Multi-Threading Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first

More information

04-Java Multithreading

04-Java Multithreading 04-Java Multithreading Join Google+ community http://goo.gl/u7qvs You can ask all your doubts, questions and queries by posting on this G+ community during/after webinar http://openandroidlearning.org

More information

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal Java Threads What is a Thread? Individual and separate unit of execution that is part of a process multiple threads can work together to accomplish a common goal Video Game example one thread for graphics

More information

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Unit 4. Thread class & Runnable Interface. Inter Thread Communication Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more

More information

JAVA. Lab 12 & 13: Multithreading

JAVA. Lab 12 & 13: Multithreading JAVA Prof. Navrati Saxena TA: Rochak Sachan Lab 12 & 13: Multithreading Outline: 2 What is multithreaded programming? Thread model Synchronization Thread Class and Runnable Interface The Main Thread Creating

More information

Exam Number/Code : 1Z Exam Name: Name: Java Standard Edition 6. Demo. Version : Programmer Certified Professional Exam.

Exam Number/Code : 1Z Exam Name: Name: Java Standard Edition 6. Demo. Version : Programmer Certified Professional Exam. Exam Number/Code : 1Z0-851 Exam Name: Name: Java Standard Edition 6 Programmer Certified Professional Exam Version : Demo http://it-shiken.jp/ QUESTION 1 public class Threads2 implements Runnable { public

More information

GlobalLogic Technical Question Paper

GlobalLogic Technical Question Paper GlobalLogic Technical Question Paper What is the output of the following code when compiled and run? Select two correct answers. public class Question01 { public static void main(string[] args){ int y=0;

More information

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

Contents. 6-1 Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004

More information

Synchronization synchronization.

Synchronization synchronization. Unit 4 Synchronization of threads using Synchronized keyword and lock method- Thread pool and Executors framework, Futures and callable, Fork-Join in Java. Deadlock conditions 1 Synchronization When two

More information

COMP346 Winter Tutorial 4 Synchronization Semaphores

COMP346 Winter Tutorial 4 Synchronization Semaphores COMP346 Winter 2015 Tutorial 4 Synchronization Semaphores 1 Topics Synchronization in Details Semaphores Introducing Semaphore.java 2 Synchronization What is it? An act of communication between unrelated

More information

Multithreading Pearson Education, Inc. All rights reserved.

Multithreading Pearson Education, Inc. All rights reserved. 1 23 Multithreading 2 23.1 Introduction Multithreading Provides application with multiple threads of execution Allows programs to perform tasks concurrently Often requires programmer to synchronize threads

More information

JAVA EXAMPLES - SOLVING DEADLOCK

JAVA EXAMPLES - SOLVING DEADLOCK JAVA EXAMPLES - SOLVING DEADLOCK http://www.tutorialspoint.com/javaexamples/thread_deadlock.htm Copyright tutorialspoint.com Problem Description: How to solve deadlock using thread? Solution: Following

More information

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

Practical No: 1 Aim: Demonstrate round - robin scheduling using threads.

Practical No: 1 Aim: Demonstrate round - robin scheduling using threads. Practical No: 1 Aim: Demonstrate round - robin scheduling using threads. Source Code: RR.java import java.io.*; class job implements Runnable int process_id, no_of_instr,time_quantum; Thread t; job(int

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes

More information

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing

More information

Software Practice 1 - Multithreading

Software Practice 1 - Multithreading Software Practice 1 - Multithreading What is the thread Life cycle of thread How to create thread Thread method Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin Oh Junseong Lee

More information

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

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization

More information

Threads and Java Memory Model

Threads and Java Memory Model Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing

More information

CS 556 Distributed Systems

CS 556 Distributed Systems CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that

More information

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors Howard Barringer Room KB2.20: email: Howard.Barringer@manchester.ac.uk February 2009 Outline Monitors FSP Models-to-Java Monitors Producers/Consumers

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void

More information

Michele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Concurrency Issues

Michele Van Dyne MUS 204B https://katie.mtech.edu/classes/csci136. Concurrency Issues Michele Van Dyne MUS 204B mvandyne@mtech.edu https://katie.mtech.edu/classes/csci136 Concurrency Issues Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core)

More information

Programming Java. Multithreaded Programming

Programming Java. Multithreaded Programming Programming Multithreaded Programming Incheon Paik 1 Contents An Overview of Threads Creating Threads Synchronization Deadlock Thread Communication 2 An Overview of Threads What is a Thread? A sequence

More information

http://www.ugrad.cs.ubc.ca/~cs219/coursenotes/threads/intro.html http://download.oracle.com/docs/cd/e17409_01/javase/tutorial/essential/concurrency/index.html start() run() class SumThread extends

More information

System Programming. Practical Session 4: Threads and Concurrency / Safety

System Programming. Practical Session 4: Threads and Concurrency / Safety System Programming Practical Session 4: Threads and Concurrency / Safety Using Threads - All the computer programs you've seen so far were sequential only one thing was performed at any given time - Sometimes

More information

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

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

COE518 Lecture Notes Week 7 (Oct 17, 2011)

COE518 Lecture Notes Week 7 (Oct 17, 2011) coe518 (Operating Systems) Lecture Notes: Week 7 Page 1 of 10 COE518 Lecture Notes Week 7 (Oct 17, 2011) Topics multithreading in Java Note: Much of this material is based on http://download.oracle.com/javase/tutorial/essential/concurrency/

More information

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;

More information

shared objects monitors run() Runnable start()

shared objects monitors run() Runnable start() Thread Lecture 18 Threads A thread is a smallest unit of execution Each thread has its own call stack for methods being invoked, their arguments and local variables. Each virtual machine instance has at

More information

Concurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Concurrency.   CSCI 136: Fundamentals of Computer Science II Keith Vertanen Concurrency http://csunplugged.org/routing-and-deadlock CSCI 136: Fundamentals of Computer Science II Keith Vertanen Overview Multi-threaded programs Multiple simultaneous paths of execution Seemingly

More information

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand

More information

Amity School of Engineering

Amity School of Engineering Amity School of Engineering B.Tech., CSE(5 th Semester) Java Programming Topic: Multithreading ANIL SAROLIYA 1 Multitasking and Multithreading Multitasking refers to a computer's ability to perform multiple

More information

JAVA - MULTITHREADING

JAVA - MULTITHREADING JAVA - MULTITHREADING http://www.tutorialspoint.com/java/java_multithreading.htm Copyright tutorialspoint.com Java is amultithreaded programming language which means we can develop mult it hreaded program

More information

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2016 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information

Concurrency. Fundamentals of Computer Science

Concurrency.  Fundamentals of Computer Science Concurrency http://csunplugged.org/routing-and-deadlock Fundamentals of Computer Science Outline Multi-threaded programs Multiple simultaneous paths of execution Seemingly at once (single core) Actually

More information

Multithreading using Java. Dr. Ferdin Joe John Joseph

Multithreading using Java. Dr. Ferdin Joe John Joseph Multithreading using Java Dr. Ferdin Joe John Joseph 1 Agenda Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing Shared Resources Synchronisation Assignment

More information

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 8 Nadia Polikarpova Quiz 1: What is printed? (Java) class MyTask implements Runnable { «Everything is ok! public

More information

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading Course Name: Advanced Java Lecture 7 Topics to be covered Multithreading Thread--An Introduction Thread A thread is defined as the path of execution of a program. It is a sequence of instructions that

More information

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

Lecture 35. Threads. Reading for next time: Big Java What is a Thread? Lecture 35 Threads Reading for next time: Big Java 21.4 What is a Thread? Imagine a Java program that is reading large files over the Internet from several different servers (or getting data from several

More information

Component-Based Software Engineering

Component-Based Software Engineering Component-Based Software Engineering More stuff on Threads Paul Krause Lecture 7 - Contents Basics of threads and synchronization Waiting - releasing locks Collection Plate example Choices when pausing

More information

CS180 Review. Recitation Week 15

CS180 Review. Recitation Week 15 CS180 Review Recitation Week 15 Announcement Final exam will be held on Thursday(12/17) 8:00~10:00 AM The coverage is comprehensive Project 5 is graded. Check your score in Blackboard. Classes and Methods

More information

Problems with Concurrency. February 19, 2014

Problems with Concurrency. February 19, 2014 with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings

More information

Testpassport.

Testpassport. Testpassport http://www.testpassport.cn Exam : 310-065 Title : Sun Certified Programmer for the Java 2 Platform. SE6.0 Version : DEMO 1 / 15 1. Given: 1. public class Threads2 implements Runnable { 2.

More information

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2019 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information

package p1; public class Derivation extends Protection { public Derivation() { System.out.println("Derived class constructor");

package p1; public class Derivation extends Protection { public Derivation() { System.out.println(Derived class constructor); PROGRAM:1 WAP to implement the packages //package 1: package p1; public class Protection int n=1; public int n_pub=2; private int n_pri=3; protected int n_pro=4; public Protection () System.out.println("Base

More information

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

More information

Multithreaded Programming

Multithreaded Programming core programming Multithreaded Programming 1 2001-2003 Marty Hall, Larry Brown http:// 2 Multithreaded Programming Agenda Why threads? Approaches for starting threads Separate class approach Callback approach

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Note: Each loop has 5 iterations in the ThreeLoopTest program. Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called

More information

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING UNIT IV MULTITHREADING AND GENERIC PROGRAMMING Differences between multithreading and multitasking, thread life cycle, creating threads, creating threads, synchronizing threads, Inter-thread communication,

More information

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar Design Patterns MSc in Computer Science Produced by Eamonn de Leastar (edeleastar@wit.ie)! Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) M257 MTA Spring2010 Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) 1. If we need various objects that are similar in structure, but

More information

Concurrent Programming: Threads. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Concurrent Programming: Threads. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Concurrent Programming: Threads CS 180 Sunil Prabhakar Department of Computer Science Purdue University Objectives This week we will get introduced to concurrent programming Creating a new thread of execution

More information

830512@itri.org.tw import java.net.socket; import java.net.serversocket; import java.io.ioexception; /* ---------- Java Server ---------- */ public class Nets static Socket thesocket; static ServerThread

More information

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

Concurrent Computing CSCI 201 Principles of Software Development

Concurrent Computing CSCI 201 Principles of Software Development Concurrent Computing CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Threads Multi-Threaded Code CPU Scheduling Program USC CSCI 201L Thread Overview Looking

More information

PASS4TEST IT 인증시험덤프전문사이트

PASS4TEST IT 인증시험덤프전문사이트 PASS4TEST IT 인증시험덤프전문사이트 http://www.pass4test.net 일년동안무료업데이트 Exam : 1z0-809 Title : Java SE 8 Programmer II Vendor : Oracle Version : DEMO Get Latest & Valid 1z0-809 Exam's Question and Answers 1 from

More information

Programming Language Concepts: Lecture 11

Programming Language Concepts: Lecture 11 Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

Question1 (10 points) : Patron Aggregator

Question1 (10 points) : Patron Aggregator NSY102 Une idée de solution Conception de logiciels Intranet : Patrons et Canevas. Session de Juillet 2010-durée : 2 heures Tous documents papiers autorisés Cnam / Paris-HTO & FOD Sommaire : Question 1

More information

CS193k, Stanford Handout #8. Threads 3

CS193k, Stanford Handout #8. Threads 3 CS193k, Stanford Handout #8 Spring, 2000-01 Nick Parlante Threads 3 t.join() Wait for finish We block until the receiver thread exits its run(). Use this to wait for another thread to finish. The current

More information

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread

More information

Java Threads. What Are Threads? General-purpose solution for managing concurrency. Multiple independent execution streams. Shared state.

Java Threads. What Are Threads? General-purpose solution for managing concurrency. Multiple independent execution streams. Shared state. Java Threads What Are Threads? Shared state (variables, files) Threads General-purpose solution for managing concurrency. Multiple independent execution streams Shared state SoftEng Group 1 What Are Threads

More information

Java Barrier Synchronizers: CountDownLatch (Part 1)

Java Barrier Synchronizers: CountDownLatch (Part 1) Java Barrier Synchronizers: CountDownLatch (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,

More information

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions? Project Threads Synchronization Minimum submission Deadline extended to tonight at midnight Early submitters 10 point bonus TSP Still due on Tuesday! Before we begin Plan for today Thread synchronization

More information

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

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption

More information

Java Barrier Synchronizers: CyclicBarrier (Part 1)

Java Barrier Synchronizers: CyclicBarrier (Part 1) Java Barrier Synchronizers: CyclicBarrier (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville,

More information

Advanced Concepts of Programming

Advanced Concepts of Programming Berne University of Applied Sciences E. Benoist / E. Dubuis January 2005 1 Multithreading in Java Java provides the programmer with built-in threading capabilities The programmer can create and manipulate

More information

By: Abhishek Khare (SVIM - INDORE M.P)

By: Abhishek Khare (SVIM - INDORE M.P) By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology UNIT-2 Interface,Multithreading,Exception Handling Interfaces : defining an interface, implementing & applying

More information

Remote Method Invocation

Remote Method Invocation Remote Method Invocation RMI Dr. Syed Imtiyaz Hassan Assistant Professor, Deptt. of CSE, Jamia Hamdard (Deemed to be University), New Delhi, India. s.imtiyaz@jamiahamdard.ac.in 1 Agenda Introduction Creating

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

Animation Part 2: MoveableShape interface & Multithreading

Animation Part 2: MoveableShape interface & Multithreading Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply

More information

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications CISC 4700 L01 Network & Client-Server Programming Spring 2016 Cowell Chapter 15: Writing Threaded Applications Idea: application does simultaneous activities. Example: web browsers download text and graphics

More information

Parallel Programming Practice

Parallel Programming Practice Parallel Programming Practice Threads and Tasks Susanne Cech Previtali Thomas Gross Last update: 2009-10-29, 09:12 Thread objects java.lang.thread Each thread is associated with an instance of the class

More information

Techniques of Java Programming: Concurrent Programming in Java

Techniques of Java Programming: Concurrent Programming in Java Techniques of Java Programming: Concurrent Programming in Java Manuel Oriol May 11, 2006 1 Introduction Threads are one of the fundamental structures in Java. They are used in a lot of applications as

More information

Threads in JDK Bruce Eckel MindView, Inc. Training & Project Reviews

Threads in JDK Bruce Eckel MindView, Inc.  Training & Project Reviews Threads in JDK 5 2004 Bruce Eckel MindView, Inc. www.mindview.net Training & Project Reviews Bruce@EckelObjects.com I ll put these slides on the site: http://mindview.net/etc/ebig Bruce Eckel Understanding

More information

Midterm assessment - MAKEUP Fall 2010

Midterm assessment - MAKEUP Fall 2010 M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:

More information

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019

Common Java Concurrency pitfalls. Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 Common Java Concurrency pitfalls Presented by : Kunal Sinha Austin Java Users Group 03/26/2019 About me Seasoned software engineer primarily working in the area of Identity and access management. Spent

More information

Program #3 - Airport Simulation

Program #3 - Airport Simulation CSCI212 Program #3 - Airport Simulation Write a simulation for a small airport that has one runway. There will be a queue of planes waiting to land and a queue of planes waiting to take off. Only one plane

More information

Principles of Software Construction: Concurrency, Part 2

Principles of Software Construction: Concurrency, Part 2 Principles of Software Construction: Concurrency, Part 2 Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Homework 5a due now Homework 5 framework goals: Functionally correct Well documented

More information

Object-Oriented Programming Concepts-15CS45

Object-Oriented Programming Concepts-15CS45 Chethan Raj C Assistant Professor Dept. of CSE Module 04 Contents 1. Multi Threaded Programming 2. Multi Threaded Programming 3. What are threads 4. How to make the classes threadable 5. Extending threads

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

Single processor CPU. Memory I/O

Single processor CPU. Memory I/O Lec 17 Threads Single processor CPU Memory I/O Multi processes Eclipse PPT iclicker Multi processor CPU CPU Memory I/O Multi-core Core Core Core Core Processor Memory I/O Logical Cores Multi-threaded

More information

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION COMP 346 WINTER 2018 1 Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION REVIEW - MULTITHREADING MODELS 2 Some operating system provide a combined user level thread and Kernel level thread facility.

More information

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Information Science and Engineering

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Information Science and Engineering INTERNAL ASSESSMENT TEST 2 Date : 28-09-15 Max Marks :50 Subject & Code : JAVA&J2EE(10IS753) Section: VII A&B Name of faculty : Mr.Sreenath M V Time : 11.30-1.00 PM Note: Answer any five questions 1) a)

More information

Concurrency and Java Programming

Concurrency and Java Programming Concurrency and Java Programming What is Concurrent Programming? Concurrent programming involves using features of the Java VM that allow parts of your program to run in parallel with each other. This

More information

MULTI-THREADING

MULTI-THREADING MULTI-THREADING KEY OBJECTIVES After completing this chapter readers will be able to understand what multi-threaded programs are learn how to write multi-threaded programs learn how to interrupt, suspend

More information

A First Parallel Program

A First Parallel Program A First Parallel Program Chapter 4 Primality Testing A simple computation that will take a long time. Whether a number x is prime: Decide whether a number x is prime using the trial division algorithm.

More information

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

More information

JAVA RMI. Remote Method Invocation

JAVA RMI. Remote Method Invocation 1 JAVA RMI Remote Method Invocation 2 Overview Java RMI is a mechanism that allows one to invoke a method on an object that exists in another address space. The other address space could be: On the same

More information

Multithreaded OO. Questions:

Multithreaded OO. Questions: Multithreaded OO Questions: 1 1. What s the following Applet code snippet doing? Also, which statement is establishing the network connection? public void actionperformed( ActionEvent evt ) { try { String

More information