CPL 2016, week 6. Asynchronous execution. Oleg Batrashev. March 14, Institute of Computer Science, Tartu, Estonia

Size: px
Start display at page:

Download "CPL 2016, week 6. Asynchronous execution. Oleg Batrashev. March 14, Institute of Computer Science, Tartu, Estonia"

Transcription

1 CPL 2016, week 6 Asynchronous execution Oleg Batrashev Institute of Computer Science, Tartu, Estonia March 14, 2016

2 Overview Studied so far: 1. Inter-thread visibility: JMM 2. Inter-thread synchronization: locks and monitors 3. Thread management: executors, tasks, cancelation 4. Inter-thread communication: confinements, queues, back pressure 5. Inter-thread collaboration: actors, inboxes, state diagrams Today: Asynchronous execution: callbacks, Pyramid of Doom, Java 8 promises. Next weeks: Performance considerations: asynchronous IO, Java 8 streams.

3 Asynchronous execution 118/145 Why asynchronous - Outline Asynchronous execution Why asynchronous Callback hell Lambdas in Java 8 Promises in Java 8 Promises within actors Promise libraries

4 Asynchronous execution 119/145 Why asynchronous - Synchronous vs asynchronous Synchronous execution algorithm executes sequentially, one step after another in single thread res1 = dosomething1 () res2 = dosomething2 ( res1 ) res3 = dosomething3 ( res1 ) print ( res2 + res3 ) dosomething3 executes after dosomething2 even with optimizations, think of the execution this way Asynchronous execution parts of the algorithm run separately, possibly in different threads execute dosomething2 and dosomething3 in separate threads and wait for their results solvable with Java Futures execute them in separate threads but release this thread until res2 and res3 are available, then execute printing not solvable with Java Futures

5 Asynchronous execution 120/145 Why asynchronous - Problems of synchronous execution parallelism in the algorithm is not utilized (solved with Java futures) current thread is not released even if nothing to do, consider res1 = dorequest1 () res2 = dorequest2 ( res1 ) print ( res2 ) if the thread is waiting for the result of request 1, it has nothing else to do the thread is not released, it may not be used elsewhere e.g. making network requests or waiting for data from web clients requires the same number of threads solution: release the thread between dorequest1() and dorequest2() how to do that?

6 Asynchronous execution 121/145 Why asynchronous - Authentication example: the algorithm Need for an algorithm with several steps that run over a network. Authentication with the salt and hash digest: 1. Client provides his name 2. Server checks if the name is ok and returns the salt the salt is just any random string 3. Client combines the salt and his password into single string, it then computes the hash for it. The hash is sent to the server. hash is a sequence of bytes 4. Server compares received hash with the locally computed hash. If they are equal, then the password was correct. The server sends resulting response to the client. password is in the server database 5. Client knows whether the authentication was successful Advantage: the password is never sent over the network.

7 Asynchronous execution 122/145 Why asynchronous - Authentication example: synchronous code // send user name conn. sendmessage ( new AuthComm. LoginRequest (" Oleg " )); // receive params or result response Message <Type > m1 = conn. readmessage (); if (m1. type == Type. RES_RESULT ) { ResultResponse m = ( ResultResponse ) m1; System. out. println (" Success "+m); return ; { // send password digest ParamsResponse m = ( ParamsResponse ) m1; MessageDigest digestalgo = MessageDigest. getinstance (" SHA -1"); String password = " mypassword "; byte [] digest = digestalgo. digest (( m. salt + password ). getbytes () conn. sendmessage ( new AuthComm. AuthRequest ( digest )); // receive result response Message <Type > m2 = conn. readmessage (); { ResultResponse m = ( ResultResponse ) m2; System. out. println (" Success "+m); return ;

8 Asynchronous execution 123/145 Callback hell - Outline Asynchronous execution Why asynchronous Callback hell Lambdas in Java 8 Promises in Java 8 Promises within actors Promise libraries

9 Asynchronous execution 124/145 Callback hell - Callback solution give the method another one which should be executed when the operations completes dorequest1 ( callback1 ); void callback1 ( res1 ) { dorequest2 ( res1, callback2 ); void callback2 ( res2 ) { print ( res2 ); put into inline callbacks results in Pyramid of Doom (not Java code!) dorequest1 ( void callback1 ( res1 ) { dorequest2 ( res1, void callback2 ( res2 ) { print ( res2 ); ); );

10 Asynchronous execution 125/145 Callback hell - Authentication example: callbacks response with the salt to the login request public interface ParamsCallback { void onsalt ( String salt ); public void login ( String username, ParamsCallback paramscallback, ResultCallback resultcallback ) response with result to the auth request public interface ResultCallback { void onsuccess (); void onfailure ( String error ); public void authenticate ( byte [] digest, ResultCallback callback ) login may result in failure through the result callback: if the username is invalid

11 Asynchronous execution 126/145 Callback hell - Authentication example: Pyramid of Doom Java callbacks are 2 level, because they are in interfaces // send user name authproxy. login (" Oleg ", new ParamsCallback () { public void onsalt ( String salt ) { // send password digest String password = " mypassword "; byte [] digest = algo. digest (( salt + password ). getbytes ()); authproxy. authenticate ( digest, new ResultCallback () { public void onsuccess () { System. out. println (" Login was successful "); public void onfailure ( String error ) { System. out. println (" Login failed : "+ error ); );, null ); not pleasant to read, not reusable last null is the callback where error handling for login should happen, omitted here

12 Asynchronous execution 127/145 Callback hell - Named callbacks explicit classes: reusable code, but more difficult to follow public void run () { // send user name authproxy. login (" Oleg ", new ParamsCallbackImpl (), null ); class ParamsCallbackImpl implements ParamsCallback { public void onsalt ( String salt ) { // send password digest String password = " mypassword "; byte [] digest = algo. digest (( salt + password ). getbytes ()); authproxy. authenticate ( digest, new ResultCallbackImpl ()); class ResultCallbackImpl implements ResultCallback { public void onsuccess () { System. out. println (" Login was successful "); public void onfailure ( String error ) { System. out. println (" Login failed : " + error ); imagine if callbacks are split between different files

13 Asynchronous execution 128/145 Callback hell - Callback summary asynchronous execution requires code that will be executed later callbacks inline callbacks result in the Pyramid of Doom, which is unpleasant to read named callbacks split sequential logic into separate methods, which is even more difficult to follow Java callback as an object with method adds 2 levels to the Pyramid of Doom Java 8 solutions: Java 8 promises (CompletableFuture) solve the problem with unreadable and hard to follow code Java 8 lambdas solve the problem of 2-level callbacks

14 Asynchronous execution 129/145 Lambdas in Java 8 - Outline Asynchronous execution Why asynchronous Callback hell Lambdas in Java 8 Promises in Java 8 Promises within actors Promise libraries

15 Asynchronous execution 130/145 Lambdas in Java 8 - Java 8 lambdas Syntactic sugar for inline methods: (arg1,arg2, arg3 ) -> { code ;..; return res ; It is possible to write: Runnable r = ()-> System. out. println (" hello "); Callable < String > c1 = ()->" hello "; Callable < String > c2 = ()-> { System. out. println ("in c2"); return " hello "; ; r. run (); c1. call (); c2. call (); However, the following is invalid, because need an interface: Object o = ()-> System. out. println (" hello "); The target type of this expression must be a functional interface Java makes methods out of interface implementations functional interface[1, sec 1.3] must contain single method declaration

16 Asynchronous execution 131/145 Lambdas in Java 8 - Java 8 method references Java 8 provides nice way to reference methods as functional interfaces: obj::methodname this::methodname ClassName::staticMethodName java.util.function interfaces: Function < Integer, Integer > m1 = Math :: abs ; BiFunction < Random, Integer, Integer > m2 = Random :: nextint ; BiConsumer < PrintStream, char [] > m3 = PrintStream :: print ;

17 Asynchronous execution 132/145 Lambdas in Java 8 - Lambdas in Pyramid of Doom // send user name authproxy. login (" Oleg ", salt -> { // Java8 lambda // send password digest String password = " mypassword "; byte [] digest = algo. digest (( salt + password ). getbytes ()); authproxy. authenticate ( digest, new ResultCallback () { public void onsuccess () { System. out. println (" Login was successful "); public void onfailure ( String error ) { System. out. println (" Login failed : "+ error ); );, null ); problem with success/failure result, interface should contain single method failure handling at each call may pollute the code Java 8 provides error forwarding for promises

18 Asynchronous execution 133/145 Promises in Java 8 - Outline Asynchronous execution Why asynchronous Callback hell Lambdas in Java 8 Promises in Java 8 Promises within actors Promise libraries

19 Asynchronous execution 134/145 Promises in Java 8 - Problems of Java Future Java Future is the result of task execution it provides the result once execution is completed must submit a task before you can have its future what if want to return the future for the task executed third in the sequence of async steps Java Future does not provide fut.runthiscallback(callback) methods i.e. can only wait with fut.get() blocking the thread Java 8 CompletableFuture (promise): may be completed at any time by promise.complete(res) only first result is preserved and valid have a bunch of promise.thenapply(callback) methods all registered callbacks are executed when promise is completed

20 Asynchronous execution 135/145 Promises in Java 8 - Java 8 CompletableFuture java.util.concurrent.completablefuture<result> like Java Future completed once but no specific task required use complete(), completeexceptionally(), cancel() like java Future may be waited with get() or get(t,unit) unlike Java Futures continuations may be added to it CF <Void > thenrun ( Runnable action ) CF <Void > thenaccept ( Consumer <? super T> action ) CF <U> thenapply ( Function <? super T,? extends U> fn) CF <U> thencompose ( Function <? super T,? extends CompletionStage <U>> fn) CF <U> handle ( BiFunction <? super T, Throwable,? extends U> fn) CF <T> whencomplete ( BiConsumer <? super T,? super Throwable > action ) the callbacks are executed after the promise is completed create the promise completedfuture(), runasync(), supplyasync()

21 Asynchronous execution 136/145 Promises in Java 8 - Apply vs compose After a promise has completed run a function with the result: apply callback returns (? extends U) compose callback returns (? extends CompletionStage<U>) both take value of type T from the source promise Imagine we have CompletableFuture<String> is a username we get asynchronously (e.g. receive from network) Want to check the validity of a username: 1. Boolean checklocally(string username) only validates that characters are ok, may be done synchronously 2. CF<Boolean> checkremotely(string username) validates that username exists in a database, the result comes asynchronously Need to use apply in the first case and compose in the second: 1. unamepromise.thenapply(this::checklocally) 2. unamepromise.thencompose(this::checkremotely) Otherwise, compose returns CF<CF<Boolean> > need to flatten

22 Asynchronous execution 137/145 Promises in Java 8 - Handle vs whencomplete whencomplete() returns the old future i.e. it invokes the callback, but does not enhance the callback chain handle() does return the new future this may be used to run actions when async action defined in the handle method completes

23 Asynchronous execution 138/145 Promises in Java 8 - Authentication example: promise chaining use thencompose and handle to chain promises error in the chain is propagated to the last promise omitting all subsequent callbacks in the chain // send user name CompletableFuture < String > saltpromise = authproxy. login (" Oleg "); CompletableFuture <Void > resultpromise = saltpromise. thencompose ( salt -> { // send password digest String password = " mypassword "; byte [] digest = algo. digest (( salt + password ). getbytes ()); return authproxy. authenticate ( digest ); ); // handle all errors or final success resultpromise. handle (( v, err ) -> { if ( err == null ) System. out. println (" Login was successful "); else System. out. println (" Login failed : "+ err ); return null ; );

24 Asynchronous execution 139/145 Promises in Java 8 - Promise chaining with separate methods easier to see the overall process public void doauth () throws IOException { authproxy. connect (" localhost ", 5000); CompletableFuture. completedfuture (" Oleg "). thencompose ( authproxy :: login ). thencompose ( this :: sendhashfromsaltandpassword ). handle ( this :: printresult ); CompletableFuture <Void > sendhashfromsaltandpassword ( String salt ) { // send password digest String password = " mypassword "; byte [] digest = digestalgo. digest (( salt + password ). getbytes ()); return authproxy. authenticate ( digest ); Void printresult ( Void v, Throwable err ) { if ( err == null ) System. out. println (" Login was successful "); else System. out. println (" Login failed : "+ err ); return null ;

25 Asynchronous execution 140/145 Promises within actors - Outline Asynchronous execution Why asynchronous Callback hell Lambdas in Java 8 Promises in Java 8 Promises within actors Promise libraries

26 Asynchronous execution 141/145 Promises within actors - Promise executors Almost all methods provide 3 flavors, e.g. for run: CF <Void > thenrun ( Runnable action ); CF <Void > thenrunasync ( Runnable action ); CF <Void > thenrunasync ( Runnable action, Executor executor ); action may be executed in the thread that has completed the promise action is executed by the ForkJoinPool.commonPool() action is executed by the provided executor We must think about the consequences of synchronization or the lack of it!

27 Asynchronous execution 142/145 Promises within actors - Promises within actors actor is inherently asynchronous its logic is split between message handling code pieces often it is more convenient to program sequence of actions, like with authentication use promise chains inside an actor Pay attention: callbacks must be executed in the actor thread, current state is not automatically checked when the callback is executed, consider promise (chain) cancellation if done from the actor thread, the rest of the promise chain won t be executed

28 Asynchronous execution 143/145 Promise libraries - Outline Asynchronous execution Why asynchronous Callback hell Lambdas in Java 8 Promises in Java 8 Promises within actors Promise libraries

29 Asynchronous execution 144/145 Promise libraries - Libraries Akka futures RxJava ReactiveX

30 Asynchronous execution 145/145 Promise libraries - Summary asynchronous execution is necessary to utilize more resources and release threads when not needed callbacks allow to continue execution, but it results in Pyramid of Doom or very scattered callback code Java futures help with resource utilization but not thread release Java 8 completable future (promise) solves the problem allow to add callbacks through the then*() methods callbacks are called in other threads, which is especially critical for actors

Overview of Advanced Java 8 CompletableFuture Features (Part 2)

Overview of Advanced Java 8 CompletableFuture Features (Part 2) Overview of Advanced Java 8 CompletableFuture Features (Part 2) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated

More information

Using Java CompletionStage in Asynchronous Programming

Using Java CompletionStage in Asynchronous Programming Using Java CompletionStage in Asynchronous Programming DEV4798 Douglas Surber Oracle Database JDBC Architect Database Server Technologies October 25, 2018 Safe Harbor Statement The following is intended

More information

Completable Future. Srinivasan Raghavan Senior Member of Technical Staff Java Platform Group

Completable Future. Srinivasan Raghavan Senior Member of Technical Staff Java Platform Group Completable Future Srinivasan Raghavan Senior Member of Technical Staff Java Platform Group Program Agenda 1 2 3 4 java.util.future Introduction Cloud Services Design and the fight for Performance CompletableFuture

More information

Overview of Advanced Java 8 CompletableFuture Features (Part 3)

Overview of Advanced Java 8 CompletableFuture Features (Part 3) Overview of Advanced Java 8 CompletableFuture Features (Part 3) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Professor of Computer Science Institute for Software Integrated

More information

Asynchronous API with CompletableFuture

Asynchronous API with CompletableFuture Asynchronous API with CompletableFuture Performance Tips and Tricks Sergey Kuksenko Java Platform Group, Oracle November, 2017 Safe Harbor Statement The following is intended to outline our general product

More information

Asynchronous API with CompletableFuture

Asynchronous API with CompletableFuture Asynchronous API with CompletableFuture Performance Tips and Tricks Sergey Kuksenko Java Platform Group, Oracle October, 2017 Safe Harbor Statement The following is intended to outline our general product

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

An overview of (a)sync & (non-) blocking

An overview of (a)sync & (non-) blocking An overview of (a)sync & (non-) blocking or why is my web-server not responding? with funny fonts! Experiment & reproduce https://github.com/antonfagerberg/play-performance sync & blocking code sync &

More information

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

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Lecture 24: Java Threads,Java synchronized statement

Lecture 24: Java Threads,Java synchronized statement COMP 322: Fundamentals of Parallel Programming Lecture 24: Java Threads,Java synchronized statement Zoran Budimlić and Mack Joyner {zoran, mjoyner@rice.edu http://comp322.rice.edu COMP 322 Lecture 24 9

More information

Introduction to Coroutines. Roman Elizarov elizarov at JetBrains

Introduction to Coroutines. Roman Elizarov elizarov at JetBrains Introduction to Coroutines Roman Elizarov elizarov at JetBrains Asynchronous programming How do we write code that waits for something most of the time? A toy problem Kotlin 1 fun requesttoken(): Token

More information

PIC 20A Streams and I/O

PIC 20A Streams and I/O PIC 20A Streams and I/O Ernest Ryu UCLA Mathematics Last edited: December 7, 2017 Why streams? Often, you want to do I/O without paying attention to where you are reading from or writing to. You can read

More information

Final Concurrency. Oleg October 27, 2014

Final Concurrency. Oleg October 27, 2014 Final Concurrency Oleg Šelajev @shelajev oleg@zeroturnaround.com October 27, 2014 Feedbacks Task Executors Fork-Join framework Completable Future Agenda 2 HOMEWORK 4 FEEDBACK THREAD LOCAL VARIABLES TASK

More information

ECE 587 Hardware/Software Co-Design Lecture 07 Concurrency in Practice Shared Memory I

ECE 587 Hardware/Software Co-Design Lecture 07 Concurrency in Practice Shared Memory I ECE 587 Hardware/Software Co-Design Spring 2018 1/15 ECE 587 Hardware/Software Co-Design Lecture 07 Concurrency in Practice Shared Memory I Professor Jia Wang Department of Electrical and Computer Engineering

More information

Dining philosophers (cont)

Dining philosophers (cont) Administrivia Assignment #4 is out Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in labs this week for a demo time Office hour today will be cut short (11:30) Another faculty

More information

Internet Technology 2/7/2013

Internet Technology 2/7/2013 Sample Client-Server Program Internet Technology 02r. Programming with Sockets Paul Krzyzanowski Rutgers University Spring 2013 To illustrate programming with TCP/IP sockets, we ll write a small client-server

More information

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem

COMP 322: Fundamentals of Parallel Programming. Lecture 30: Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 30: Java Synchronizers, Dining Philosophers Problem Vivek Sarkar, Shams Imam Department of Computer Science, Rice University Contact email: vsarkar@rice.edu,

More information

CS Programming Languages: Scala

CS Programming Languages: Scala CS 3101-2 - Programming Languages: Scala Lecture 6: Actors and Concurrency Daniel Bauer (bauer@cs.columbia.edu) December 3, 2014 Daniel Bauer CS3101-2 Scala - 06 - Actors and Concurrency 1/19 1 Actors

More information

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University Lecture 2 COMP1406/1006 (the Java course) Fall 2013 M. Jason Hinek Carleton University today s agenda a quick look back (last Thursday) assignment 0 is posted and is due this Friday at 2pm Java compiling

More information

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Writing a Simple Java Program Intro to Variables Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch

More information

Reaktive Anwendungen mit RxJava. Dr. Michael Menzel

Reaktive Anwendungen mit RxJava. Dr. Michael Menzel Reaktive Anwendungen mit RxJava Dr. Michael Menzel DIGITALIZATION DIGITALIZATION DIGITALIZATION DIGITALIZATION REACTIVE ARCHITECTURES How can we build highly interactive (responsive) systems, which are

More information

CS 351 Design of Large Programs Programming Abstractions

CS 351 Design of Large Programs Programming Abstractions CS 351 Design of Large Programs Programming Abstractions Brooke Chenoweth University of New Mexico Spring 2019 Searching for the Right Abstraction The language we speak relates to the way we think. The

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

Spring MVC 4.x Spring 5 Web Reactive

Spring MVC 4.x Spring 5 Web Reactive Part 1 Spring MVC 4.x Spring 5 Web Reactive Rossen Stoyanchev @rstoya05 Spring MVC 4.3 Reactive programming for Java devs Spring 5 Web Reactive Shortcut Annotations @RequestMapping @GetMapping @PostMapping

More information

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries

More information

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

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12

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

Introduction to Functional Programming in Java 8

Introduction to Functional Programming in Java 8 1 Introduction to Functional Programming in Java 8 Java 8 is the current version of Java that was released in March, 2014. While there are many new features in Java 8, the core addition is functional programming

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright

Java Basics. Object Orientated Programming in Java. Benjamin Kenwright Java Basics Object Orientated Programming in Java Benjamin Kenwright Outline Essential Java Concepts Syntax, Grammar, Formatting, Introduce Object-Orientated Concepts Encapsulation, Abstract Data, OO Languages,

More information

CompSci 125 Lecture 02

CompSci 125 Lecture 02 Assignments CompSci 125 Lecture 02 Java and Java Programming with Eclipse! Homework:! http://coen.boisestate.edu/jconrad/compsci-125-homework! hw1 due Jan 28 (MW), 29 (TuTh)! Programming:! http://coen.boisestate.edu/jconrad/cs125-programming-assignments!

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

CSCI 201L Written Exam #1 Fall % of course grade

CSCI 201L Written Exam #1 Fall % of course grade Final Score /15 Name SOLUTION ID Extra Credit /0.5 Lecture Section (circle one): TTh 8:00-9:20 TTh 9:30-10:50 TTh 11:00-12:20 CSCI 201L Written Exam #1 Fall 2017 15% of course grade The exam is one hour

More information

Java Concurrency For Humans. Cay Horstmann Author of Core Java (10 editions since 1996)

Java Concurrency For Humans. Cay Horstmann Author of Core Java (10 editions since 1996) Java Concurrency For Humans Cay Horstmann Author of Core Java (10 editions since 1996) Outline Audience: Application programmers Goal: Modern Concurrency Constructs Executors and Futures Asynchronous Processing

More information

JAX-RS and CDI Bike the (ReacIve) Bridge CON2549

JAX-RS and CDI Bike the (ReacIve) Bridge CON2549 JAX-RS and CDI Bike the (ReacIve) Bridge CON2549 David Delabassée (@delabassee) - Oracle José Paumard (@josepaumard) - Consultant October, 2017 2 @delabassee 3 @JosePaumard @JosePaumard https://github.com/josepaumard

More information

ECE 122 Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Introduction to Programming for ECE Lecture 1 Course Overview Welcome! What is this class about? Java programming somewhat software somewhat Solving engineering

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

Actors in the Small. Making Actors more Useful. Bill La

Actors in the Small. Making Actors more Useful. Bill La Actors in the Small Making Actors more Useful Bill La Forge laforge49@gmail.com @laforge49 Actors in the Small I. Introduction II. Making Actors Fast III.Making Actors Easier to Program IV. Tutorial I.

More information

JS Event Loop, Promises, Async Await etc. Slava Kim

JS Event Loop, Promises, Async Await etc. Slava Kim JS Event Loop, Promises, Async Await etc Slava Kim Synchronous Happens consecutively, one after another Asynchronous Happens later at some point in time Parallelism vs Concurrency What are those????

More information

Lambda Expressions and Java 8 Streams. Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh. Contents of this talk.

Lambda Expressions and Java 8 Streams. Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh. Contents of this talk. Java 8 s and Java 8 van den Hombergh Fontys Hogeschool voor Techniek en Logistiek February 23, 2017 and /FHTenL s and Java 8 February 23, 2017 1/28 talk Expression and Internal/External Iteration Java

More information

Types II. Hwansoo Han

Types II. Hwansoo Han Types II Hwansoo Han Arrays Most common and important composite data types Homogeneous elements, unlike records Fortran77 requires element type be scalar Elements can be any type (Fortran90, etc.) A mapping

More information

Computational Expression

Computational Expression Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

More information

Algorithms & Datastructures Laboratory Exercise Sheet 1

Algorithms & Datastructures Laboratory Exercise Sheet 1 Algorithms & Datastructures Laboratory Exercise Sheet 1 Wolfgang Pausch Heiko Studt René Thiemann Tomas Vitvar

More information

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

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014 Question One: Choose the correct answer and write it on the external answer booklet. 1. Java is. a. case

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CMSC 433 Programming Language Technologies and Paradigms. Concurrency CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.

More information

Stuart

Stuart Clojure Time Stuart Halloway stu@clojure.com @stuarthalloway Copyright 2007-2010 Relevance, Inc. This presentation is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United

More information

Fontys Hogeschool voor Techniek en Logistiek. March 13, 2018

Fontys Hogeschool voor Techniek en Logistiek. March 13, 2018 Java 8 s and Java 8 Fontys Hogeschool voor Techniek en Logistiek March 13, 2018 and? /FHTenL s and Java 8 March 13, 2018 1/34 talk The other anonymous and? Java 8 and? /FHTenL s and Java 8 March 13, 2018

More information

CT 229 Fundamentals of Java Syntax

CT 229 Fundamentals of Java Syntax CT 229 Fundamentals of Java Syntax 19/09/2006 CT229 New Lab Assignment Monday 18 th Sept -> New Lab Assignment on CT 229 Website Two Weeks for Completion Due Date is Oct 1 st Assignment Submission is online

More information

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked exceptions Java try statement Final wishes Java try-resource

More information

Chapter 4: Processes. Process Concept. Process State

Chapter 4: Processes. Process Concept. Process State Chapter 4: Processes Process Concept Process Scheduling Operations on Processes Cooperating Processes Interprocess Communication Communication in Client-Server Systems 4.1 Process Concept An operating

More information

CS September 2017

CS September 2017 Machine vs. transport endpoints IP is a network layer protocol: packets address only the machine IP header identifies source IP address, destination IP address Distributed Systems 01r. Sockets Programming

More information

INF5750. Introduction to JavaScript and Node.js

INF5750. Introduction to JavaScript and Node.js INF5750 Introduction to JavaScript and Node.js Outline Introduction to JavaScript Language basics Introduction to Node.js Tips and tools for working with JS and Node.js What is JavaScript? Built as scripting

More information

COMP6700/2140 Code as Data

COMP6700/2140 Code as Data COMP6700/2140 Code as Data Alexei B Khorev Research School of Computer Science, ANU March 2017 Alexei B Khorev (RSCS, ANU) COMP6700/2140 Code as Data March 2017 1 / 19 Topics 1 What does treating code

More information

JDBC Next A new asynchronous API for connecting to a database

JDBC Next A new asynchronous API for connecting to a database JDBC Next A new asynchronous API for connecting to a database Douglas Surber Kuassi Mensah JDBC Architect Director, Product Management Database Server Technologies April 18, 2017 Safe Harbor Statement

More information

Chapter 4: Threads. Operating System Concepts 9 th Edition

Chapter 4: Threads. Operating System Concepts 9 th Edition Chapter 4: Threads Silberschatz, Galvin and Gagne 2013 Chapter 4: Threads Overview Multicore Programming Multithreading Models Thread Libraries Implicit Threading Threading Issues Operating System Examples

More information

6.092: Java for 6.170

6.092: Java for 6.170 6.092: Java for 6.170 Lucy Mendel MIT EECS MIT 6.092 IAP 2006 1 Course Staff Lucy Mendel Corey McCaffrey Rob Toscano Justin Mazzola Paluska Scott Osler Ray He Ask us for help! MIT 6.092 IAP 2006 2 Class

More information

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

More information

1007 Imperative Programming Part II

1007 Imperative Programming Part II Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be

More information

ADBA Asynchronous Database Access

ADBA Asynchronous Database Access ADBA Asynchronous Database Access A new asynchronous API for connecting to a database Douglas Surber Kuassi Mensah JDBC Architect Director, Product Management Database Server Technologies July 18, 2018

More information

Architecture using Functional Programming concepts < + >

Architecture using Functional Programming concepts < + > Architecture using Functional Programming concepts < + > Jorge Castillo @JorgeCastilloPr 1 2 Kotlin and Functional Programming FP means concern separation (declarative computations vs runtime execution),

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem Mack Joyner and Zoran Budimlić {mjoyner, zoran}@rice.edu http://comp322.rice.edu

More information

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes Based on Introduction to Java Programming, Y. Daniel Liang, Brief Version, 10/E 1 Creating Classes and Objects Classes give us a way of defining custom data types and associating data with operations on

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

Chapter 2. Network Chat

Chapter 2. Network Chat Chapter 2. Network Chat In a multi-player game, different players interact with each other. One way of implementing this is to have a centralized server that interacts with each client using a separate

More information

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information

Lecture 11.1 I/O Streams

Lecture 11.1 I/O Streams 21/04/2014 Ebtsam AbdelHakam 1 OBJECT ORIENTED PROGRAMMING Lecture 11.1 I/O Streams 21/04/2014 Ebtsam AbdelHakam 2 Outline I/O Basics Streams Reading characters and string 21/04/2014 Ebtsam AbdelHakam

More information

Cover Page. The handle holds various files of this Leiden University dissertation

Cover Page. The handle   holds various files of this Leiden University dissertation Cover Page The handle http://hdl.handle.net/1887/45620 holds various files of this Leiden University dissertation Author: Nobakht, Behrooz Title: Actors at work Issue Date: 2016-12-15 Programming with

More information

IGL S AND MOUNT NS. Taking AKKA to Production

IGL S AND MOUNT NS. Taking AKKA to Production IGL S AND MOUNT NS Taking AKKA to Production THIS TALK Hello! I m Derek Wyatt, Senior Platform Developer at Auvik Networks! and author of Akka Concurrency Scala, Play and Akka form the foundational triad

More information

Reactive Streams in the Web. Florian Stefan ebay Classifieds Group GOTO Berlin 2017

Reactive Streams in the Web. Florian Stefan ebay Classifieds Group GOTO Berlin 2017 Reactive Streams in the Web Florian Stefan ebay Classifieds Group GOTO Berlin 2017 Who am I? Florian Stefan mobile.de (ebay Classifieds Group) https://ebaytech.berlin/ fstefan@ebay.com @f_s_t_e_f_a_n https://github.com/florian-stefan/

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours: CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Tuesday 10:00 AM 12:00 PM * Wednesday 4:00 PM 5:00 PM Friday 11:00 AM 12:00 PM OR

More information

Chapter 4: Threads. Operating System Concepts 9 th Edition

Chapter 4: Threads. Operating System Concepts 9 th Edition Chapter 4: Threads Silberschatz, Galvin and Gagne 2013 Chapter 4: Threads Overview Multicore Programming Multithreading Models Thread Libraries Implicit Threading Threading Issues Operating System Examples

More information

PIC 20A The Basics of Java

PIC 20A The Basics of Java PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and

More information

Reactive programming: origins & ecosystem. Jonas Chapuis, Ph.D.

Reactive programming: origins & ecosystem. Jonas Chapuis, Ph.D. Reactive programming: origins & ecosystem Jonas Chapuis, Ph.D. Timeline Functional Reactive Animation (Fran Library, Haskell) Rx 1.0 for.net, Erik Meijer & team at Microsoft Elm language Rx for Java, Netflix

More information

Swift 5, ABI Stability and

Swift 5, ABI Stability and Swift 5, ABI Stability and Concurrency @phillfarrugia Important Documents Concurrency Manifesto by Chris Lattner https: /gist.github.com/lattner/ 31ed37682ef1576b16bca1432ea9f782 Kicking off Concurrency

More information

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised

More information

Java Threads and intrinsic locks

Java Threads and intrinsic locks Java Threads and intrinsic locks 1. Java and OOP background fundamentals 1.1. Objects, methods and data One significant advantage of OOP (object oriented programming) is data encapsulation. Each object

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

[module lab 1.3] CANCELLATION AND SHUTDOWN

[module lab 1.3] CANCELLATION AND SHUTDOWN v1.0 BETA Sistemi Concorrenti e di Rete LS II Facoltà di Ingegneria - Cesena a.a 2008/2009 [module lab 1.3] CANCELLATION AND SHUTDOWN 1 STOPPING THREADS AND TASKS An activity is cancellable if external

More information

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

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

File I/O Array Basics For-each loop

File I/O Array Basics For-each loop File I/O Array Basics For-each loop 178 Recap Use the Java API to look-up classes/method details: Math, Character, String, StringBuffer, Random, etc. The Random class gives us several ways to generate

More information

About this exam review

About this exam review Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review

More information

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

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Threads SPL/2010 SPL/20 1

Threads SPL/2010 SPL/20 1 Threads 1 Today Processes and Scheduling Threads Abstract Object Models Computation Models Java Support for Threads 2 Process vs. Program processes as the basic unit of execution managed by OS OS as any

More information

Byte and Character Streams. Reading and Writing Console input and output

Byte and Character Streams. Reading and Writing Console input and output Byte and Character Streams Reading and Writing Console input and output 1 I/O basics The io package supports Java s basic I/O (input/output) Java does provide strong, flexible support for I/O as it relates

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

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void

More information

The Java ExecutorService (Part 1)

The Java ExecutorService (Part 1) The Java ExecutorService (Part 1) Douglas C. Schmidt d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA Learning

More information

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B 1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these 2. How many primitive data types are there in Java? A. 5 B. 6 C. 7 D. 8 3. In Java byte, short, int and long

More information

I/O in Haskell. To output a character: putchar :: Char -> IO () e.g., putchar c. To output a string: putstr :: String -> IO () e.g.

I/O in Haskell. To output a character: putchar :: Char -> IO () e.g., putchar c. To output a string: putstr :: String -> IO () e.g. I/O in Haskell Generally, I/O functions in Haskell have type IO a, where a could be any type. The purpose and use of a will be explained later. We call these commands or actions, for we think of them as

More information

OCaml Language Choices CMSC 330: Organization of Programming Languages

OCaml Language Choices CMSC 330: Organization of Programming Languages OCaml Language Choices CMSC 330: Organization of Programming Languages! Implicit or explicit declarations?! Explicit variables must be introduced with let before use! But you don t need to specify types

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

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

Java Workshop Lambda Expressions

Java Workshop Lambda Expressions Java Workshop Lambda Expressions AP Java Workshop 2015 Hanno Hüther and Martin Stein Agenda 1. Origin and syntax 2. History and motivation 3. Exercise 1: Refactoring to lambdas 4. Method references 5.

More information