7. Liveness and Asynchrony Prof. O. Nierstrasz. Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based.

Slides:



Advertisements
Similar presentations
Three types of remote process invocation
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap Overview:  Syntax and Semantics  Semantics of Expressions.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Sources  Cay Horstmann, Computing.
ESE Einführung in Software Engineering 6. Modeling Objects and Classes Prof. O. Nierstrasz.
ESE Einführung in Software Engineering 7. Modeling Behaviour Prof. O. Nierstrasz.
Introduction to Software Engineering 7. Modeling Behaviour.
CP — Concurrent Programming 8. Liveness and Asynchrony Prof. O. Nierstrasz Wintersemester 2005 / 2006.
OORPT Object-Oriented Reengineering Patterns and Techniques 7. Problem Detection Prof. O. Nierstrasz.
7. Liveness and Asynchrony Prof. O. Nierstrasz. Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based.
10. Petri Nets Prof. O. Nierstrasz. Roadmap  Definition: —places, transitions, inputs, outputs —firing enabled transitions  Modelling: —concurrency.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Object-Oriented Reengineering Patterns and Techniques Prof. O. Nierstrasz Prof. S. Ducasse T.
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap  Syntax and Semantics  Semantics of Expressions 
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
DISTRIBUTED AND HIGH-PERFORMANCE COMPUTING CHAPTER 7: SHARED MEMORY PARALLEL PROGRAMMING.
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.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Overview  Common errors … —Typical.
ESE Einführung in Software Engineering N. XXX Prof. O. Nierstrasz Fall Semester 2009.
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
The Software Composition Group Prof. O. Nierstrasz
13. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Summary, Trends, Research...  Summary: functional, logic and object-oriented.
Remote Procedure Call in SR Programming Language By Tze-Kin Tsang 3/20/2000.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed lambda calculus.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Overview  Common errors … —Typical.
13. A bit of Smalltalk. © Oscar Nierstrasz 2 Roadmap  The origins of Smalltalk  What is Smalltalk?  Syntax in a nutshell  Seaside — web development.
CP — Concurrent Programming 12. Petri Nets Prof. O. Nierstrasz Wintersemester 2005 / 2006.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Metamodeling Seminar X. CHAPTER Prof. O. Nierstrasz Spring Semester 2008.
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
N. XXX Prof. O. Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap Overview  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Sources  Cay Horstmann, Computing.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed lambda calculus.
CP — Concurrent Programming 3. Safety and Synchronization Prof. O. Nierstrasz Wintersemester 2005 / 2006.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© S. Demeyer, S. Ducasse, O. Nierstrasz Chapter.1 MakeMoney Corp. C*O of MakeMoney Corp. Our Vision  We invest in software  We do not know software 
OORPT Object-Oriented Reengineering Patterns and Techniques X. CHAPTER Prof. O. Nierstrasz.
CP — Concurrent Programming X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
12. eToys. © O. Nierstrasz PS — eToys 12.2 Denotational Semantics Overview:  … References:  …
Fundamentals of Python: From First Programs Through Data Structures
Multithreading.
Smart Reference Proxy Provides additional actions whenever an object is referenced (e.g., counting the number of references to the object) Firewall Proxy.
7. Just In Time Compilation Prof. O. Nierstrasz Jan Kurs.
CS 390- Unix Programming Environment CS 390 Unix Programming Environment Topics to be covered: Distributed Computing Fundamentals.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
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.
1 Lecture 5 (part2) : “Interprocess communication” n reasons for process cooperation n types of message passing n direct and indirect message passing n.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Synchronizing threads, thread pools, etc.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
About the Author A Lifetime of Software Development Started Writing Code at Age 11 Programming Summer Camp at Age 12 Writing Code Ever Since At Age 25,
CP — Concurrent Programming 6. Liveness and Guarded Methods Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Multi Threading.
Prof. Leonardo Mostarda University of Camerino
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Lecture 4: RPC Remote Procedure Call CDK: Chapter 5
Threads in Java James Brucker.
Threads and concurrency / Safety
Presentation transcript:

7. Liveness and Asynchrony Prof. O. Nierstrasz

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 2

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 3

© Oscar Nierstrasz Liveness and Asynchrony 4 Pattern: Asynchronous Invocations Intent: Avoid waiting for a request to be serviced by decoupling sending from receiving. Applicability  When a host object can distribute services amongst multiple helper objects.  When an object does not immediately need the result of an invocation to continue doing useful work.  When invocations that are logically asynchronous, regardless of whether they are coded using threads.  During refactoring, when classes and methods are split in order to increase concurrency and reduce liveness problems.

© Oscar Nierstrasz Liveness and Asynchrony 5 Asynchronous Invocations — template Asynchronous invocation typically looks like this: abstract class AbstractHost implements Host { public void service() { pre();// code to run before invocation invokeHelper();// the invocation during();// code to run in parallel post();// code to run after completion }... } // A host provides a service public interface Host { public void service(); } Asynchrony

Asynchronous Invocations — design steps Consider the following issues: Does the Host need results back from the Helper? Not if, e.g., the Helper returns results directly to the Host’s caller! Can the Host process new requests while the Helper is running? Might depend on the kind of request... Can the Host do something while the Helper is running? i.e., in the during() code Does the Host need to synchronize pre- invocation processing? i.e., if service() is guarded or if pre() updates the Host’s state Does the Host need to synchronize post-invocation processing? i.e., if post() updates the Host’s state Does post-invocation processing only depend on the Helper’s result?... or does the host have to wait for other conditions? Is the same Helper always used?Is a new one generated to help with each new service request? © Oscar Nierstrasz Liveness and Asynchrony 6

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 7

Simple Relays — three variants A relay method obtains all its functionality by delegating to the helper, without any pre(), during(), or post() actions.  Direct invocations: —Invoke the Helper directly, but without synchronization  Thread-based messages: —Create a new thread to invoke the Helper  Command-based messages: —Pass the request to another object that will run it © Oscar Nierstrasz Liveness and Asynchrony 8 Relays are commonly seen in Adaptors.

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 9

Variant: Direct invocations © Oscar Nierstrasz Liveness and Asynchrony 10 public class HostDirectRelay implements Host { // NB: Helper is also immutable, so unsynchronized protected final Helper helper = new CountingHelper(); public void service() { // unsynchronized! invokeHelper();// stateless method } protected void invokeHelper() { helper.help();// unsynchronized! } Asynchrony is achieved by avoiding synchronization. The Host is free to accept other requests, while the Host’s caller must wait for the reply. Asynchrony

© Oscar Nierstrasz Liveness and Asynchrony 11 Direct invocations... If helper is mutable, it can be protected with an accessor: public class HostDirectRelaySyncHelper implements Host { protected Helper helper; public void service() { invokeHelper(); } protected void invokeHelper() { helper().help();// partially unsynchronized! } protected synchronized Helper helper() { return helper; } public synchronized void setHelper(String name) { helper = new NamedHelper(name); }

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 12

© Oscar Nierstrasz Liveness and Asynchrony 13 Variant: Thread-based messages The invocation can be performed within a new thread: public class HostWithHelperThread implements Host {... protected void invokeHelper() { new Thread() { public void run() { helper.help(); } }.start(); }... }

© Oscar Nierstrasz Liveness and Asynchrony 14 Thread-based messages... The cost of evaluating Helper.help() should outweigh the overhead of creating a thread!  If the Helper is a daemon (loops endlessly)  If the Helper does I/O  Possibly, if multiple helper methods are invoked Typical application: web servers

© Oscar Nierstrasz Liveness and Asynchrony 15 Thread-per-message Gateways The Host may construct a new Helper to service each request. public class FileIO { public void writeBytes(String file, byte[] data) { new Thread (new FileWriter(file, data)).start(); } public void readBytes(...) {... } } class FileWriter implements Runnable { private String nm_;// hold arguments private byte[] d_; public FileWriter(String name, byte[] data) {... } public void run() {... }// write to file... }

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 16

© Oscar Nierstrasz Liveness and Asynchrony 17 Variant: Command-based messages The Host can also put a Command object in a queue for another object that will invoke the Helper: Command-based forms are especially useful for:  scheduling of helpers (i.e., by pool of threads)  undo and replay capabilities  transporting messages over networks public class HostEventQueue implements Host { …protected void invokeHelper() { EventQueue.invokeLater(new Runnable() { public void run() { helper.help(); } }); } }

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 18

© Oscar Nierstrasz Liveness and Asynchrony 19 Tail calls Applies when the helper method is the last statement of a service. Only pre() code is synchronized. public class TailCallSubject extends Observable { protected Observer observer = new Observer() {... }; protected double state; public void updateState(double d) {// unsynchronized doUpdate(d); // partially synchronized sendNotification();// unsynchronized } protected synchronized void doUpdate(double d) {// synchronized state = d; } protected void sendNotification() {// unsynchronized observer.update(this, state); } NB: The host is immediately available to accept new requests Asynchrony

© Oscar Nierstrasz Liveness and Asynchrony 20 Tail calls with new threads Alternatively, the tail call may be made in a separate thread: public synchronized void updateState(double d) { state = d; new Thread() { public void run() { observer.update(TailCallSubject.this, state); } }.start(); }

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 21

Early Reply © Oscar Nierstrasz Liveness and Asynchrony 22 Early reply is a built-in feature in some programming languages. It can be easily simulated when it is not a built-in feature. Early reply allows a host to perform useful activities after returning a result to the client:

© Oscar Nierstrasz Liveness and Asynchrony 23 Simulating Early Reply A one-slot buffer can be used to pick up the reply from a helper thread: A one-slot buffer is a simple abstraction that can be used to implement many higher-level concurrency abstractions...

© Oscar Nierstrasz Liveness and Asynchrony 24 Early Reply in Java public class EarlyReplyDemo {... public Object service() {// unsynchronized final Slot reply = new Slot(); final EarlyReplyDemo host = this; new Thread() {// Helper public void run() { synchronized (host) { reply.put(host.compute()); host.cleanup();// retain lock } }.start(); return reply.get(); // early reply }... } Asynchrony

Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based messages  Tail calls  Early replies  Futures © Oscar Nierstrasz Liveness and Asynchrony 25

© Oscar Nierstrasz Liveness and Asynchrony 26 Futures Futures allow a client to continue in parallel with a host until the future value is needed:

A Future Class © Oscar Nierstrasz Liveness and Asynchrony 27 abstract class Future { private Result result;// initially null public Future(final Argument arg) { new Thread() { public void run() { setResult(computeResult(arg)); } }.start(); } abstract protected Result computeResult(Argument arg); public synchronized void setResult(Result val) { result = val; notifyAll(); return; } public synchronized Result result() { while (result == null) { try { wait(); } catch (InterruptedException e) { } } return result; } Asynchrony

© Oscar Nierstrasz Liveness and Asynchrony 28 Using Futures in Java Without special language support, the client must explicitly request a result() from the future object. Future f = new Future (n) { protected synchronized Integer computeResult(Integer n) { return fibonacci(n); } // slow, naive algorithm to force long compute times ;-) public int fibonacci(int n) { if (n<2) { return 1; } else { return fibonacci(n-1) + fibonacci(n-2); } } }; int val = f.result();

© Oscar Nierstrasz Liveness and Asynchrony 29 What you should know!  What general form does an asynchronous invocation take?  When should you consider using asynchronous invocations?  In what sense can a direct invocation be “asynchronous”?  Why (and how) would you use inner classes to implement asynchrony?  What is “early reply”, and when would you use it?  What are “futures”, and when would you use them?  How can implement futures and early replies in Java?

© Oscar Nierstrasz Liveness and Asynchrony 30 Can you answer these questions?  Why might you want to increase concurrency on a single-processor machine?  Why are servers commonly structured as thread-per- message gateways?  Which of the concurrency abstractions we have discussed till now can be implemented using one-slot- buffers as the only synchronized objects?  When are futures better than early replies? Vice versa?

License © Oscar Nierstrasz 31 Attribution-ShareAlike 2.5 You are free: to copy, distribute, display, and perform the work to make derivative works to make commercial use of the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. For any reuse or distribution, you must make clear to others the license terms of this work. Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. Liveness and Asynchrony