SlideShare a Scribd company logo
Asynchronous Programming
ESUG 2024, Lille, France
James Foster
Agenda
u Asynchronous Programming and Synchronization
u Exploring Other Languages
u Exploring Smalltalk Implementations
u Observations
u Questions
Asynchronous Programming and
Synchronization
Futures and Promises
Synchronous: Blocking
u Blocking & Sequential
Asynchronous:
Nonblocking and Parallel
u Blocking & Sequential u Nonblocking & Parallel
Fork
Asynchronous:
Nonblocking and Concurrent
u Blocking & Sequential u Nonblocking & Parallel
Fork
u Nonblocking & Concurrent
Fork
Synchronization
u Coordinating multiple processes to join up.
Fork
Join
Web Server
Asynchronous Programming in GemStone
u Demo of WebGS with parallel sessions
Futures and Promises
u "In computer science, future, promise, delay,
and deferred refer to constructs used for synchronizing
program execution in some concurrent programming
languages. They describe an object that acts as a proxy
for a result that is initially unknown, usually because
the computation of its value is not yet complete."
u — https://en.wikipedia.org/wiki/Futures_and_promises
Exploring Other Languages
Futures and Promises
JavaScript: Promises
u A Promise is in one of these states:
u Pending: Initial state, neither fulfilled nor rejected.
u Fulfilled: The operation completed successfully.
u Rejected: The operation failed.
JavaScript: Example
let promise = new Promise(function(resolve, reject) {
// Asynchronous operation here
if (/* operation successful */) {
resolve(value); // Resolve with a value
} else {
reject(error); // Reject with an error
}
});
promise.then(
function(value) { /* handle a successful operation */ },
function(error) { /* handle an error */ }
);
JavaScript: Summary
• Creating a Promise: The Promise constructor is used to create a promise. It
takes a function (executor) that should start an asynchronous operation and
eventually call either the resolve (to indicate success) or reject (to indicate
failure) function to settle the promise.
• Consuming a Promise: The .then() method is used to attach callbacks to
handle the fulfillment or rejection of the promise. The .catch() method is used
to handle rejection, and .finally() method allows you to execute logic
regardless of the promise's outcome.
• Chaining Promises: Promises can be chained to perform a series of
asynchronous operations in sequence. Each .then() returns a new promise,
allowing for further methods to be called in sequence.
JavaScript: Conclusion
u Promises are a core part of asynchronous programming in
JavaScript, making it easier to work with asynchronous
operations by avoiding the complexity of nested callbacks,
known as "callback hell."
Python: ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor, as_completed
def task(n):
return n + 1
# Create a ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=5) as executor:
# Submit tasks to the executor
futures = [executor.submit(task, i) for i in range(5)]
# Wait for the futures to complete and get their results
for future in as_completed(futures):
print(future.result())
Python: asyncio.Future
import asyncio
async def set_after(fut, delay, value):
# Wait
await asyncio.sleep(delay)
# Set the result
fut.set_result(value)
async def main():
# Create a Future object
fut = asyncio.Future()
# Schedule the future
await set_after(fut, 1, 'hello!')
# Wait for the future
print(await fut)
asyncio.run(main())
Java: CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// Create a CompletableFuture
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
// Simulate a long-running job
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Hello";
});
// Chain a computation stage
CompletableFuture<String> greetingFuture =
future.thenApply(result -> result + ", World!");
// Block and get the result
System.out.println(greetingFuture.get()); // Prints "Hello, World!" after 1 second
}
}
Dart: async and await
u A long running method is (should be!) annotated with async.
u An async method returns a Future.
u A callback may be added to a Future to handle:
u A normal result; or,
u An error.
u Instead of adding a callback, you can await for a Future to complete.
u This will block, so should not be done in the primary (UI) thread.
u In background threads this allows synchronous (linear) code.
import 'dart:async';
Future<String> fetchUserOrder() async {
// Simulate a network request to fetch a user order
await Future.delayed(Duration(seconds: 2));
return 'Cappuccino';
}
void main() async {
print('Fetching user order...');
try {
// Wait for the Future to complete and extract its result
String order = await fetchUserOrder();
print('Your order is: $order');
} catch (err) {
print('Failed to fetch user order: $err');
}
}
Exploring Smalltalk Implementations
Not exhaustive!
VAST Platform
u Modeled on Dart
u Demo
Pharo
u Semaphore approach
u TaskIt package
u Demo
Glamorous Toolkit
u Documentation
Observations
u Application developers
u Avoid long-running (blocking) tasks in the UI thread.
u Futures/Promises simplify the handling of asynchronous tasks.
u Library developers
u Use Futures/Promises for long-running operations (disk, network, etc.)
u Force application developers to use Futures!
Questions?
u James.Foster@GemTalkSystems.com
u VP of Finance and Operations, GemTalk Systems LLC
u James.Foster@WallaWalla.edu
u Associate Professor of Computer Science, Walla Walla University

More Related Content

PPTX
Mobile Application Development class 008
PDF
Leveraging Completable Futures to handle your query results Asynchrhonously
ODP
Scala Future & Promises
PPTX
AsynchronousProgrammingDesignPatterns.pptx
PPTX
Async programming and python
PDF
Leverage CompletableFutures to handle async queries. DevNexus 2022
PDF
Using Akka Futures
PDF
Asynchronous development in JavaScript
Mobile Application Development class 008
Leveraging Completable Futures to handle your query results Asynchrhonously
Scala Future & Promises
AsynchronousProgrammingDesignPatterns.pptx
Async programming and python
Leverage CompletableFutures to handle async queries. DevNexus 2022
Using Akka Futures
Asynchronous development in JavaScript

Similar to Asynchronous Programming. Talk from ESUG2024 (20)

DOCX
Asynchronyin net
PDF
Javascript internals
ODP
Java Concurrency
PDF
PyCon Canada 2019 - Introduction to Asynchronous Programming
PPTX
Ddd melbourne 2011 C# async ctp
PPT
Node.js: CAMTA Presentation
PPT
Server side JavaScript: going all the way
ODP
Concurrent Programming in Java
PDF
Javascript Promises/Q Library
PPTX
Windows Phone 8 - 3.5 Async Programming
PPTX
Async java8
PDF
The art of concurrent programming
PDF
Loom and concurrency latest
PPTX
Java - Concurrent programming - Thread's advanced concepts
PPTX
The JavaScript Event Loop - Concurrency in the Language of the Web
PDF
Promises look into the async future
PDF
Concurrency-5.pdf
PDF
Advanced JavaScript - Internship Presentation - Week6
PDF
Introduction to Python Asyncio
PDF
Java concurrency
Asynchronyin net
Javascript internals
Java Concurrency
PyCon Canada 2019 - Introduction to Asynchronous Programming
Ddd melbourne 2011 C# async ctp
Node.js: CAMTA Presentation
Server side JavaScript: going all the way
Concurrent Programming in Java
Javascript Promises/Q Library
Windows Phone 8 - 3.5 Async Programming
Async java8
The art of concurrent programming
Loom and concurrency latest
Java - Concurrent programming - Thread's advanced concepts
The JavaScript Event Loop - Concurrency in the Language of the Web
Promises look into the async future
Concurrency-5.pdf
Advanced JavaScript - Internship Presentation - Week6
Introduction to Python Asyncio
Java concurrency
Ad

More from ESUG (20)

PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PDF
Micromaid: A simple Mermaid-like chart generator for Pharo
PDF
Directing Generative AI for Pharo Documentation
PDF
Even Lighter Than Lightweiht: Augmenting Type Inference with Primitive Heuris...
PDF
Composing and Performing Electronic Music on-the-Fly with Pharo and Coypu
PDF
Gamifying Agent-Based Models in Cormas: Towards the Playable Architecture for...
PDF
Analysing Python Machine Learning Notebooks with Moose
PDF
FASTTypeScript metamodel generation using FAST traits and TreeSitter project
PDF
Migrating Katalon Studio Tests to Playwright with Model Driven Engineering
PDF
Package-Aware Approach for Repository-Level Code Completion in Pharo
PDF
Evaluating Benchmark Quality: a Mutation-Testing- Based Methodology
PDF
An Analysis of Inline Method Refactoring
PDF
Identification of unnecessary object allocations using static escape analysis
PDF
Control flow-sensitive optimizations In the Druid Meta-Compiler
PDF
Clean Blocks (IWST 2025, Gdansk, Poland)
PDF
Encoding for Objects Matters (IWST 2025)
PDF
Challenges of Transpiling Smalltalk to JavaScript
PDF
Immersive experiences: what Pharo users do!
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
PDF
Cavrois - an Organic Window Management (ESUG 2025)
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
Micromaid: A simple Mermaid-like chart generator for Pharo
Directing Generative AI for Pharo Documentation
Even Lighter Than Lightweiht: Augmenting Type Inference with Primitive Heuris...
Composing and Performing Electronic Music on-the-Fly with Pharo and Coypu
Gamifying Agent-Based Models in Cormas: Towards the Playable Architecture for...
Analysing Python Machine Learning Notebooks with Moose
FASTTypeScript metamodel generation using FAST traits and TreeSitter project
Migrating Katalon Studio Tests to Playwright with Model Driven Engineering
Package-Aware Approach for Repository-Level Code Completion in Pharo
Evaluating Benchmark Quality: a Mutation-Testing- Based Methodology
An Analysis of Inline Method Refactoring
Identification of unnecessary object allocations using static escape analysis
Control flow-sensitive optimizations In the Druid Meta-Compiler
Clean Blocks (IWST 2025, Gdansk, Poland)
Encoding for Objects Matters (IWST 2025)
Challenges of Transpiling Smalltalk to JavaScript
Immersive experiences: what Pharo users do!
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
Cavrois - an Organic Window Management (ESUG 2025)
Ad

Recently uploaded (20)

PPTX
Transform Your Business with a Software ERP System
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
medical staffing services at VALiNTRY
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Digital Systems & Binary Numbers (comprehensive )
PPT
Introduction Database Management System for Course Database
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
System and Network Administration Chapter 2
Transform Your Business with a Software ERP System
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Upgrade and Innovation Strategies for SAP ERP Customers
Odoo Companies in India – Driving Business Transformation.pdf
How to Choose the Right IT Partner for Your Business in Malaysia
Adobe Illustrator 28.6 Crack My Vision of Vector Design
medical staffing services at VALiNTRY
Which alternative to Crystal Reports is best for small or large businesses.pdf
ai tools demonstartion for schools and inter college
wealthsignaloriginal-com-DS-text-... (1).pdf
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PTS Company Brochure 2025 (1).pdf.......
L1 - Introduction to python Backend.pptx
Computer Software and OS of computer science of grade 11.pptx
Design an Analysis of Algorithms II-SECS-1021-03
Digital Systems & Binary Numbers (comprehensive )
Introduction Database Management System for Course Database
How to Migrate SBCGlobal Email to Yahoo Easily
System and Network Administration Chapter 2

Asynchronous Programming. Talk from ESUG2024

  • 1. Asynchronous Programming ESUG 2024, Lille, France James Foster
  • 2. Agenda u Asynchronous Programming and Synchronization u Exploring Other Languages u Exploring Smalltalk Implementations u Observations u Questions
  • 5. Asynchronous: Nonblocking and Parallel u Blocking & Sequential u Nonblocking & Parallel Fork
  • 6. Asynchronous: Nonblocking and Concurrent u Blocking & Sequential u Nonblocking & Parallel Fork u Nonblocking & Concurrent Fork
  • 7. Synchronization u Coordinating multiple processes to join up. Fork Join
  • 9. Asynchronous Programming in GemStone u Demo of WebGS with parallel sessions
  • 10. Futures and Promises u "In computer science, future, promise, delay, and deferred refer to constructs used for synchronizing program execution in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is not yet complete." u — https://en.wikipedia.org/wiki/Futures_and_promises
  • 12. JavaScript: Promises u A Promise is in one of these states: u Pending: Initial state, neither fulfilled nor rejected. u Fulfilled: The operation completed successfully. u Rejected: The operation failed.
  • 13. JavaScript: Example let promise = new Promise(function(resolve, reject) { // Asynchronous operation here if (/* operation successful */) { resolve(value); // Resolve with a value } else { reject(error); // Reject with an error } }); promise.then( function(value) { /* handle a successful operation */ }, function(error) { /* handle an error */ } );
  • 14. JavaScript: Summary • Creating a Promise: The Promise constructor is used to create a promise. It takes a function (executor) that should start an asynchronous operation and eventually call either the resolve (to indicate success) or reject (to indicate failure) function to settle the promise. • Consuming a Promise: The .then() method is used to attach callbacks to handle the fulfillment or rejection of the promise. The .catch() method is used to handle rejection, and .finally() method allows you to execute logic regardless of the promise's outcome. • Chaining Promises: Promises can be chained to perform a series of asynchronous operations in sequence. Each .then() returns a new promise, allowing for further methods to be called in sequence.
  • 15. JavaScript: Conclusion u Promises are a core part of asynchronous programming in JavaScript, making it easier to work with asynchronous operations by avoiding the complexity of nested callbacks, known as "callback hell."
  • 16. Python: ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor, as_completed def task(n): return n + 1 # Create a ThreadPoolExecutor with ThreadPoolExecutor(max_workers=5) as executor: # Submit tasks to the executor futures = [executor.submit(task, i) for i in range(5)] # Wait for the futures to complete and get their results for future in as_completed(futures): print(future.result())
  • 17. Python: asyncio.Future import asyncio async def set_after(fut, delay, value): # Wait await asyncio.sleep(delay) # Set the result fut.set_result(value) async def main(): # Create a Future object fut = asyncio.Future() # Schedule the future await set_after(fut, 1, 'hello!') # Wait for the future print(await fut) asyncio.run(main())
  • 19. import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureExample { public static void main(String[] args) throws ExecutionException, InterruptedException { // Create a CompletableFuture CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { // Simulate a long-running job Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Hello"; }); // Chain a computation stage CompletableFuture<String> greetingFuture = future.thenApply(result -> result + ", World!"); // Block and get the result System.out.println(greetingFuture.get()); // Prints "Hello, World!" after 1 second } }
  • 20. Dart: async and await u A long running method is (should be!) annotated with async. u An async method returns a Future. u A callback may be added to a Future to handle: u A normal result; or, u An error. u Instead of adding a callback, you can await for a Future to complete. u This will block, so should not be done in the primary (UI) thread. u In background threads this allows synchronous (linear) code.
  • 21. import 'dart:async'; Future<String> fetchUserOrder() async { // Simulate a network request to fetch a user order await Future.delayed(Duration(seconds: 2)); return 'Cappuccino'; } void main() async { print('Fetching user order...'); try { // Wait for the Future to complete and extract its result String order = await fetchUserOrder(); print('Your order is: $order'); } catch (err) { print('Failed to fetch user order: $err'); } }
  • 23. VAST Platform u Modeled on Dart u Demo
  • 24. Pharo u Semaphore approach u TaskIt package u Demo
  • 26. Observations u Application developers u Avoid long-running (blocking) tasks in the UI thread. u Futures/Promises simplify the handling of asynchronous tasks. u Library developers u Use Futures/Promises for long-running operations (disk, network, etc.) u Force application developers to use Futures!
  • 27. Questions? u James.Foster@GemTalkSystems.com u VP of Finance and Operations, GemTalk Systems LLC u James.Foster@WallaWalla.edu u Associate Professor of Computer Science, Walla Walla University