CP — Concurrent Programming 8. Liveness and Asynchrony Prof. O. Nierstrasz Wintersemester 2005 / 2006.

Slides:



Advertisements
Similar presentations
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Advertisements

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 5. Safety and Liveness Properties Prof. O. Nierstrasz Wintersemester 2005 / 2006.
OORPT Object-Oriented Reengineering Patterns and Techniques 7. Problem Detection Prof. O. Nierstrasz.
CORBA - Common Object Request Broker Architecture.
7. Liveness and Asynchrony Prof. O. Nierstrasz. Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based.
28.2 Functionality Application Software Provides Applications supply the high-level services that user access, and determine how users perceive the capabilities.
10. Petri Nets Prof. O. Nierstrasz. Roadmap  Definition: —places, transitions, inputs, outputs —firing enabled transitions  Modelling: —concurrency.
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.
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
CP — Concurrent Programming 1. Introduction Prof. O. Nierstrasz Wintersemester 2005 / 2006.
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.
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.
Fall 2007cs4251 Distributed Computing Umar Kalim Dept. of Communication Systems Engineering 31/10/2007.
Copyright W. Howden1 Lecture 19: Intro to O/O Components.
© 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.
Integration case study Week 8 – Lecture 1. Enrolment request (Workstation) Application server Database server Database New University Student Record System.
CP — Concurrent Programming 3. Safety and Synchronization Prof. O. Nierstrasz Wintersemester 2005 / 2006.
7. Liveness and Asynchrony Prof. O. Nierstrasz. Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
© 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
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.
12/1/98 COP 4020 Programming Languages Parallel Programming in Ada and Java Gregory A. Riccardi Department of Computer Science Florida State University.
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.
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.
1 Lecture 5 (part2) : “Interprocess communication” n reasons for process cooperation n types of message passing n direct and indirect message passing n.
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.
Multi Threading.
Prof. Leonardo Mostarda University of Camerino
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Transactional Memory Semaphores, monitors, and conditional critical regions all suffer from limitations based on lock semantics Naïve synchronization may.
Lecture 4: RPC Remote Procedure Call Coulouris et al: Chapter 5
CSE 451: Operating Systems Autumn 2003 Lecture 16 RPC
Lecture 4: RPC Remote Procedure Call CDK: Chapter 5
Threads in Java James Brucker.
CSE 451: Operating Systems Winter 2003 Lecture 16 RPC
Threads and concurrency / Safety
Presentation transcript:

CP — Concurrent Programming 8. Liveness and Asynchrony Prof. O. Nierstrasz Wintersemester 2005 / 2006

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.2 Liveness and Asynchrony Overview  Asynchronous invocations —Simple Relays – Direct Invocations – Thread-based messages; Gateways – Command-based messages —Tail calls —Early replies —Futures NB: most of the code examples in this lecture are skeletons only!

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.3 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 CP — Liveness and Asynchrony CP 8.4 Asynchronous Invocations — form Asynchronous invocation typically looks like this: class Host { public service() { pre();// code to run before invocation invokeHelper();// the invocation during();// code to run in parallel post();// code to run after completion } class Host { public service() { pre();// code to run before invocation invokeHelper();// the invocation during();// code to run in parallel post();// code to run after completion }

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.5 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 CP — Liveness and Asynchrony CP 8.6 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 Relays are commonly seen in Adaptors.

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.7 Variant: Direct invocations Asynchrony is achieved by avoiding synchronization. The Host is free to accept other requests, while the Host’s caller must wait for the reply. class Host { protected Helper helper_ = new Helper(); public void service() {// unsynchronized! invokeHelper();// (stateless method) } protected void invokeHelper() { helper_.help();// unsynchronized! } class Host { protected Helper helper_ = new Helper(); public void service() {// unsynchronized! invokeHelper();// (stateless method) } protected void invokeHelper() { helper_.help();// unsynchronized! }

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.8 Direct invocations... If helper_ is mutable, it can be protected with an accessor: class Host2 extends Host { protected Helper helper_ = new Helper(); protected synchronized Helper helper() { return helper_; } public void service() {// unsynchronized helper().help();// partially synchronized } class Host2 extends Host { protected Helper helper_ = new Helper(); protected synchronized Helper helper() { return helper_; } public void service() {// unsynchronized helper().help();// partially synchronized }

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.9 Variant: Thread-based messages The invocation can be performed within a new thread: protected void invokeHelper() { new Thread() {// An inner class final Helper h_ = helper_;// Must be final! public void run() { h_.help() ; } }.start() ; } protected void invokeHelper() { new Thread() {// An inner class final Helper h_ = helper_;// Must be final! public void run() { h_.help() ; } }.start() ; }

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.10 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 CP — Liveness and Asynchrony CP 8.11 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... } 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... }

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.12 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 protected EventQueue q_; protected invokeHelper() { q_.put(new HelperMessage(helper_)); } protected EventQueue q_; protected invokeHelper() { q_.put(new HelperMessage(helper_)); }

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.13 Tail calls Applies when the helper method is the last statement of a method. Only pre() code is synchronized. class Subject { protected Observer obs_ = new...; protected double state_; public void updateState(double d) {// not synched doUpdate(d); // synched sendNotification();// not synched } protected synchronized doUpdate(double d) {// synched state_ = d; } protected void sendNotification() {// not synched obs_.changeNotification(this); } class Subject { protected Observer obs_ = new...; protected double state_; public void updateState(double d) {// not synched doUpdate(d); // synched sendNotification();// not synched } protected synchronized doUpdate(double d) {// synched state_ = d; } protected void sendNotification() {// not synched obs_.changeNotification(this); } NB: The host is immediately available to accept new requests

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.14 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() { final Observer o_ = obs_; public void run() { o_.changeNotification(Subject.this); } }.start(); } public synchronized void updateState(double d) { state_ = d; new Thread() { final Observer o_ = obs_; public void run() { o_.changeNotification(Subject.this); } }.start(); }

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

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.16 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 CP — Liveness and Asynchrony CP 8.17 Early Reply in Java public class Host {... public Object service() {// unsynchronized final Slot reply = new Slot(); final Host host = this; new Thread() {// Helper public void run() { synchronized (host) { reply.put(host.compute()); host.cleanup();// retain lock } }.start(); return reply.get(); // early reply }... } public class Host {... public Object service() {// unsynchronized final Slot reply = new Slot(); final Host host = this; new Thread() {// Helper public void run() { synchronized (host) { reply.put(host.compute()); host.cleanup();// retain lock } }.start(); return reply.get(); // early reply }... }

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

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.19 A Future Class Futures can be implemented as a layer of abstraction around a shared Slot: class Future { private Object val_; // initially null private Slot slot_; // shared with some worker public Future(Slot slot) { slot_ = slot; } public Object value() { synchronized(slot_) { // avoid race conditions! if (val_ == null) val_ = slot_.get(); } return val_; } class Future { private Object val_; // initially null private Slot slot_; // shared with some worker public Future(Slot slot) { slot_ = slot; } public Object value() { synchronized(slot_) { // avoid race conditions! if (val_ == null) val_ = slot_.get(); } return val_; }

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.20 Using Futures in Java Without special language support, the client must explicitly request a value() from the future object. public Future service () {// unsynchronized final Slot slot = new Slot(); new Thread() { public void run() { slot.put(compute()); } }.start(); return new Future(slot); } protected synchronized Object compute() {... } public Future service () {// unsynchronized final Slot slot = new Slot(); new Thread() { public void run() { slot.put(compute()); } }.start(); return new Future(slot); } protected synchronized Object compute() {... }

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.21 FutureTask public FutureTask service (final int n) { FutureTask future = new FutureTask ( new Callable () { public Integer call() { return new Integer(fibonacci(n)); } }); new Thread(future).start(); // or use an Executor return future; } public FutureTask service (final int n) { FutureTask future = new FutureTask ( new Callable () { public Integer call() { return new Integer(fibonacci(n)); } }); new Thread(future).start(); // or use an Executor return future; } JUC provides a generic implementation of Futures, parameterized by Callable or Runnable services.

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.22 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 CP — Liveness and Asynchrony CP 8.23 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?

© Oscar Nierstrasz CP — Liveness and Asynchrony CP 8.24 License > 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. 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.