SlideShare a Scribd company logo
1 of 21
CONCURRENT PROGRAMMING
THREAD’S ADVANCED CONCEPTS
PROGRAMMAZIONE CONCORRENTE E DISTR.
Università degli Studi di Padova
Dipartimento di Matematica
Corso di Laurea in Informatica, A.A. 2015 – 2016
rcardin@math.unipd.it
Programmazione concorrente e distribuita
SUMMARY
 Callable tasks
 Futures
 Executors
 Executor services
 Deadlocks
2Riccardo Cardin
Programmazione concorrente e distribuita
CALLABLES
 A Callable is a Runnable, that returns a value
 The Callable type is parametrized on the type of its
return value
 Callable<Integer> represents an asynchronous
computation that will produce an Integer value
 The value computed is not directly available
 We need a type to represents a value that will be available in
the future...
 Represents a deferred computation
3Riccardo Cardin
public interface Callable<V> {
// The method can throw an exception,
// unlike Runnable run method
public V call() throws Exception;
}
Programmazione concorrente e distribuita
FUTURES
 A Future represents a computation whose
result will be available at some future time
 Start the computation, give someone the Future
object, and forget about it
 To obtain the result a synchronization is needed
 The get method blocks until the result is available
 Or until a timeout has been reached
4Riccardo Cardin
public interface Future<V> {
V get() throws . . .;
V get(long timeout, TimeUnit unit) throws . . .;
void cancel(boolean mayInterrupt);
boolean isCancelled();
boolean isDone();
}
Programmazione concorrente e distribuita
FUTURES
 Using FutureTask is possible to run a
Callable, obtaining a Future as result
 Adapter of the Runnable and Future interfaces
 Using FutureTask is possible to run a Callable using
a Thread
 Exception semantics
 ExecutionException: error during execution
 CancellationException: task was cancelled
5Riccardo Cardin
Callable<Integer> myComputation = . . .;
FutureTask<Integer> task = new FutureTask<Integer>(myComputation);
Thread t = new Thread(task); // it's a Runnable
t.start();
// . . .
Integer result = task.get(); // it's a Future
Programmazione concorrente e distribuita
FUTURES
6Riccardo Cardin
Programmazione concorrente e distribuita
FUTURES
 A Future have some interesting characteristics
 Immutable
 Once a future is completed, it will be completed forever
 Lets treat asynchronous programming in a
synchronous way
 Simplify the division of complex task into smaller ones, that
can be executed concurrently
7Riccardo Cardin
Future<Integer> future = /* Initialization */ ;
System.out.println(future.get()); // Blocks and print 42
System.out.println(future.get()); // Prints 42 again
produceSomething
startDoingSomething
doSomethingWithResult
r
Programmazione concorrente e distribuita
FUTURES
8Riccardo Cardin
Programmazione concorrente e distribuita
EXECUTORS
 Usually it doesn’t make sense to have a one-to-
one relationship between a task and a thread
 Thread is a mechanism for execution a sequence of
instructions (task)
 Creating a new thread means to ask some work to the OS, so
it is a time consuming operation
 When tasks are short lived, run many of them on the
same thread
 When tasks are computationally intensive, use one
thread per processor
 Avoid the overhead of context switching among threads
 Anyway, all that you need is a thread pool
9Riccardo Cardin
Programmazione concorrente e distribuita
EXECUTORS
 Executors are implementation of thread pools
 An homogeneous pool of worker threads
 Amortizes thread creation and teardown
 Improves responsiveness, due to lack of task execution’s delay
 Thread pools execution using static factory methods
 Each method return an executor instance that implements a
specific execution policy
10Riccardo Cardin
// Create the thread pool with a specified execution policy
Executor executor = Executors.newCachedThreadPool();
Runnable hellos = new Runnable() { /* Say hello a lot of times */ };
Runnable goodbyes =
new Runnable() {/* Say hello a lot of times */ };
// Submit task for execution to thread pool
executors.execute(hellos);
executors.execute(goodbyes);
Programmazione concorrente e distribuita
EXECUTORS
 An Executor executes tasks, choosing the
threads on which to run them
 You have not the full control on thread life cycle
 Based on the producer / consumer pattern
 Activities produce tasks, threads consume tasks
 Decoupling of task submission from task execution
 Simplier changing of execution policy
 What, where, when, and how of task execution
11Riccardo Cardin
Runnable task = new Runnable() { /* Some task */ };
Executor executor = // Get an instance to an executor
executor.execute(task); // A thread is choosen to execute the task
Programmazione concorrente e distribuita
EXECUTORS
 Execution policies
 Dependent on the available computing resources and
quality of service requirements
 In what thread will tasks be executed?
 In what order should tasks be executed (FIFO, LIFO, priority
order)?
 How many tasks may execute concurrently?
 How many tasks may be queued pending execution?
 If a task has to be rejected because the system is overloaded,
which task should be selected as the victim, and how should
the application be notified?
 What actions should be taken before or after executing a
task?
12Riccardo Cardin
Programmazione concorrente e distribuita
EXECUTORS
13Riccardo Cardin
 Available executors policies
Method Description
newCachedThreadPool New thread are created as needed; idle
threads are kept for 60 seconds
newFixedThreadPool The pool contains a fixed set of threads;
idle threads are kept indefinitely
newSingleThreadExecutor A «pool» with a single thread that executes
the submitted tasks sequentially (similar to
the Swing event dispatch thread)
newScheduledThreadPool A fixed-thread pool for scheduled execution
newSingleThreadScheduledExecutor A single-thread «pool» for scheduled
execution
Programmazione concorrente e distribuita
EXECUTORS
14Riccardo Cardin
Programmazione concorrente e distribuita
EXECUTOR SERVICES
 To execute a Callable, use an instance of the
ExecutorService interface
 Previous static factory methods return such instances
 1° submit returns a Future containing the task itself
 Control of execution (call isDone, cancel, isCancelled)
 2° submit acts like the first, but return result object
 3° submit returns a Future of the result of the Callable task
 Method invokeAll executes all the input Callables
15Riccardo Cardin
Future<?> submit(Runnable task)
Future<T> submit(Runnable task, T result)
Future<T> submit(Callable<T> task)
<T> List<Future<T>> invokeAll(Collection<? Extends Callable<T>>
task)
Tipicalworkflow
Programmazione concorrente e distribuita
EXECUTOR SERVICES
 Executor lifecycle
 Derived from the interface of ExecutorService type
16Riccardo Cardin
Running
Shutting
down
Terminated
Executors are created in running state.
In this state an executor accepts new tasks
and schedules them for execution
This state is reached after shutdown method
was called. No new task are accepted, but
previously submitted task are allowed to complete.
The shutdownNow method initiates an abrupt
shutdown: no queued task not yet begun is started
Once all task are completed, the executor
transitions to the terminated state
Programmazione concorrente e distribuita
DEADLOCKS
 Multiple threads wait forever due to a cyclic
locking dependency
 If threads are nodes and relations of dependency are
edges, a cyclic graph means to have a deadlock
 The JVM cannot detect deadlock, differently from
database systems
17Riccardo Cardin
A
R1
B
R2
C
R3 Also known as deadly embrace:
A needs a resource R hold by B, B
a resource hold by C, an so on...
Programmazione concorrente e distribuita
DEADLOCKS
 Deadlocks rarely manifest themeselves
immediatly (only in production under heavy load)
 Four conditions have to hold simultaneously (Coffman
conditions)
 Mutual exclusion: at least one resource must be held in a non-
shareable mode
 Hold and wait: a process is currently holding at least one
resource and requesting additional resources
 No preemption: a resource can be released only voluntarily
 Circular wait: a process must be waiting for a resource which is
being held by another process, which in turn is waiting for the
first process to release the resource
18Riccardo Cardin
Programmazione concorrente e distribuita
DEADLOCKS
19Riccardo Cardin
Programmazione concorrente e distribuita
EXAMPLES
20Riccardo Cardin
https://github.com/rcardin/pcd-snippets
Programmazione concorrente e distribuita
REFERENCES
 Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay
Horstmann, Gary Cornell, 2012, Prentice Hall
 Chap. 6 «Task Execution», Java Concurrency in Practice, Brian
Goetz, 2006, Addison-Wesley Professional
 Chap. 10 «Avoiding Liveness Hazards», Java Concurrency in
Practice, Brian Goetz, 2006, Addison-Wesley Professional
 Chap. 10 «Concurrent Programming», Core Java for the Impatient,
Cay Horstmann, 2015, Addison-Wesley
 Deadlocks https://en.wikipedia.org/wiki/Deadlock
21Riccardo Cardin

More Related Content

What's hot

Introduction to-vhdl
Introduction to-vhdlIntroduction to-vhdl
Introduction to-vhdlNeeraj Gupta
 
System Verilog Functional Coverage
System Verilog Functional CoverageSystem Verilog Functional Coverage
System Verilog Functional Coveragerraimi
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template PatternJonathan Simon
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Detecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJDetecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJCoen De Roover
 
System verilog coverage
System verilog coverageSystem verilog coverage
System verilog coveragePushpa Yakkala
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Coen De Roover
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Javakim.mens
 
The SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
The SOUL Tool Suite for Querying Programs in Symbiosis with EclipseThe SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
The SOUL Tool Suite for Querying Programs in Symbiosis with EclipseCoen De Roover
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareAndrey Karpov
 

What's hot (20)

Introduction to-vhdl
Introduction to-vhdlIntroduction to-vhdl
Introduction to-vhdl
 
System Verilog Functional Coverage
System Verilog Functional CoverageSystem Verilog Functional Coverage
System Verilog Functional Coverage
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
Introduction to VHDL
Introduction to VHDLIntroduction to VHDL
Introduction to VHDL
 
GCC RTL and Machine Description
GCC RTL and Machine DescriptionGCC RTL and Machine Description
GCC RTL and Machine Description
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Syntutic
SyntuticSyntutic
Syntutic
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Lecture1
Lecture1Lecture1
Lecture1
 
Detecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJDetecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJ
 
System verilog coverage
System verilog coverageSystem verilog coverage
System verilog coverage
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
The SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
The SOUL Tool Suite for Querying Programs in Symbiosis with EclipseThe SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
The SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
 
Doulos coverage-tips-tricks
Doulos coverage-tips-tricksDoulos coverage-tips-tricks
Doulos coverage-tips-tricks
 
10 strategy pattern
10 strategy pattern10 strategy pattern
10 strategy pattern
 
Behavioral modeling
Behavioral modelingBehavioral modeling
Behavioral modeling
 
Extending and scripting PDT
Extending and scripting PDTExtending and scripting PDT
Extending and scripting PDT
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
 

Viewers also liked

Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178Kai Sasaki
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVMRiccardo Cardin
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and outputRiccardo Cardin
 
Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern StrutturaliRiccardo Cardin
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics ProgrammingRiccardo Cardin
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiRiccardo Cardin
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design PatternRiccardo Cardin
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignRiccardo Cardin
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patternsRiccardo Cardin
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionRiccardo Cardin
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyBozhidar Bozhanov
 

Viewers also liked (15)

Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVM
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern Strutturali
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
Diagrammi di Sequenza
Diagrammi di SequenzaDiagrammi di Sequenza
Diagrammi di Sequenza
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei Requisiti
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design Pattern
 
Diagrammi delle Classi
Diagrammi delle ClassiDiagrammi delle Classi
Diagrammi delle Classi
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency Injection
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very ugly
 

Similar to Java - Concurrent programming - Thread's advanced concepts

Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practiceDocker, Inc.
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
What the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startupWhat the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startupGerrit Grunwald
 
Container Orchestration from Theory to Practice
Container Orchestration from Theory to PracticeContainer Orchestration from Theory to Practice
Container Orchestration from Theory to PracticeDocker, Inc.
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2ppd1961
 
Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIelliando dias
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
An introduction to_rac_system_test_planning_methods
An introduction to_rac_system_test_planning_methodsAn introduction to_rac_system_test_planning_methods
An introduction to_rac_system_test_planning_methodsAjith Narayanan
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvmaragozin
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xAndrey Karpov
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streamingphanleson
 
remote method invocation
remote method invocationremote method invocation
remote method invocationArun Nair
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)Rick Hightower
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)Rick Hightower
 
Effective java item 80 and 81
Effective java   item 80 and 81Effective java   item 80 and 81
Effective java item 80 and 81Isaac Liao
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 

Similar to Java - Concurrent programming - Thread's advanced concepts (20)

Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practice
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
What the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startupWhat the CRaC - Superfast JVM startup
What the CRaC - Superfast JVM startup
 
Container Orchestration from Theory to Practice
Container Orchestration from Theory to PracticeContainer Orchestration from Theory to Practice
Container Orchestration from Theory to Practice
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMI
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
An introduction to_rac_system_test_planning_methods
An introduction to_rac_system_test_planning_methodsAn introduction to_rac_system_test_planning_methods
An introduction to_rac_system_test_planning_methods
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvm
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
 
Java On CRaC
Java On CRaCJava On CRaC
Java On CRaC
 
remote method invocation
remote method invocationremote method invocation
remote method invocation
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
 
Effective java item 80 and 81
Effective java   item 80 and 81Effective java   item 80 and 81
Effective java item 80 and 81
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 

More from Riccardo Cardin

Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern ComportamentaliRiccardo Cardin
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern CreazionaliRiccardo Cardin
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular jsRiccardo Cardin
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principlesRiccardo Cardin
 

More from Riccardo Cardin (7)

Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern Comportamentali
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern Creazionali
 
Diagrammi di Attività
Diagrammi di AttivitàDiagrammi di Attività
Diagrammi di Attività
 
Diagrammi Use Case
Diagrammi Use CaseDiagrammi Use Case
Diagrammi Use Case
 
Introduzione a UML
Introduzione a UMLIntroduzione a UML
Introduzione a UML
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular js
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principles
 

Recently uploaded

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Java - Concurrent programming - Thread's advanced concepts

  • 1. CONCURRENT PROGRAMMING THREAD’S ADVANCED CONCEPTS PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 – 2016 rcardin@math.unipd.it
  • 2. Programmazione concorrente e distribuita SUMMARY  Callable tasks  Futures  Executors  Executor services  Deadlocks 2Riccardo Cardin
  • 3. Programmazione concorrente e distribuita CALLABLES  A Callable is a Runnable, that returns a value  The Callable type is parametrized on the type of its return value  Callable<Integer> represents an asynchronous computation that will produce an Integer value  The value computed is not directly available  We need a type to represents a value that will be available in the future...  Represents a deferred computation 3Riccardo Cardin public interface Callable<V> { // The method can throw an exception, // unlike Runnable run method public V call() throws Exception; }
  • 4. Programmazione concorrente e distribuita FUTURES  A Future represents a computation whose result will be available at some future time  Start the computation, give someone the Future object, and forget about it  To obtain the result a synchronization is needed  The get method blocks until the result is available  Or until a timeout has been reached 4Riccardo Cardin public interface Future<V> { V get() throws . . .; V get(long timeout, TimeUnit unit) throws . . .; void cancel(boolean mayInterrupt); boolean isCancelled(); boolean isDone(); }
  • 5. Programmazione concorrente e distribuita FUTURES  Using FutureTask is possible to run a Callable, obtaining a Future as result  Adapter of the Runnable and Future interfaces  Using FutureTask is possible to run a Callable using a Thread  Exception semantics  ExecutionException: error during execution  CancellationException: task was cancelled 5Riccardo Cardin Callable<Integer> myComputation = . . .; FutureTask<Integer> task = new FutureTask<Integer>(myComputation); Thread t = new Thread(task); // it's a Runnable t.start(); // . . . Integer result = task.get(); // it's a Future
  • 6. Programmazione concorrente e distribuita FUTURES 6Riccardo Cardin
  • 7. Programmazione concorrente e distribuita FUTURES  A Future have some interesting characteristics  Immutable  Once a future is completed, it will be completed forever  Lets treat asynchronous programming in a synchronous way  Simplify the division of complex task into smaller ones, that can be executed concurrently 7Riccardo Cardin Future<Integer> future = /* Initialization */ ; System.out.println(future.get()); // Blocks and print 42 System.out.println(future.get()); // Prints 42 again produceSomething startDoingSomething doSomethingWithResult r
  • 8. Programmazione concorrente e distribuita FUTURES 8Riccardo Cardin
  • 9. Programmazione concorrente e distribuita EXECUTORS  Usually it doesn’t make sense to have a one-to- one relationship between a task and a thread  Thread is a mechanism for execution a sequence of instructions (task)  Creating a new thread means to ask some work to the OS, so it is a time consuming operation  When tasks are short lived, run many of them on the same thread  When tasks are computationally intensive, use one thread per processor  Avoid the overhead of context switching among threads  Anyway, all that you need is a thread pool 9Riccardo Cardin
  • 10. Programmazione concorrente e distribuita EXECUTORS  Executors are implementation of thread pools  An homogeneous pool of worker threads  Amortizes thread creation and teardown  Improves responsiveness, due to lack of task execution’s delay  Thread pools execution using static factory methods  Each method return an executor instance that implements a specific execution policy 10Riccardo Cardin // Create the thread pool with a specified execution policy Executor executor = Executors.newCachedThreadPool(); Runnable hellos = new Runnable() { /* Say hello a lot of times */ }; Runnable goodbyes = new Runnable() {/* Say hello a lot of times */ }; // Submit task for execution to thread pool executors.execute(hellos); executors.execute(goodbyes);
  • 11. Programmazione concorrente e distribuita EXECUTORS  An Executor executes tasks, choosing the threads on which to run them  You have not the full control on thread life cycle  Based on the producer / consumer pattern  Activities produce tasks, threads consume tasks  Decoupling of task submission from task execution  Simplier changing of execution policy  What, where, when, and how of task execution 11Riccardo Cardin Runnable task = new Runnable() { /* Some task */ }; Executor executor = // Get an instance to an executor executor.execute(task); // A thread is choosen to execute the task
  • 12. Programmazione concorrente e distribuita EXECUTORS  Execution policies  Dependent on the available computing resources and quality of service requirements  In what thread will tasks be executed?  In what order should tasks be executed (FIFO, LIFO, priority order)?  How many tasks may execute concurrently?  How many tasks may be queued pending execution?  If a task has to be rejected because the system is overloaded, which task should be selected as the victim, and how should the application be notified?  What actions should be taken before or after executing a task? 12Riccardo Cardin
  • 13. Programmazione concorrente e distribuita EXECUTORS 13Riccardo Cardin  Available executors policies Method Description newCachedThreadPool New thread are created as needed; idle threads are kept for 60 seconds newFixedThreadPool The pool contains a fixed set of threads; idle threads are kept indefinitely newSingleThreadExecutor A «pool» with a single thread that executes the submitted tasks sequentially (similar to the Swing event dispatch thread) newScheduledThreadPool A fixed-thread pool for scheduled execution newSingleThreadScheduledExecutor A single-thread «pool» for scheduled execution
  • 14. Programmazione concorrente e distribuita EXECUTORS 14Riccardo Cardin
  • 15. Programmazione concorrente e distribuita EXECUTOR SERVICES  To execute a Callable, use an instance of the ExecutorService interface  Previous static factory methods return such instances  1° submit returns a Future containing the task itself  Control of execution (call isDone, cancel, isCancelled)  2° submit acts like the first, but return result object  3° submit returns a Future of the result of the Callable task  Method invokeAll executes all the input Callables 15Riccardo Cardin Future<?> submit(Runnable task) Future<T> submit(Runnable task, T result) Future<T> submit(Callable<T> task) <T> List<Future<T>> invokeAll(Collection<? Extends Callable<T>> task) Tipicalworkflow
  • 16. Programmazione concorrente e distribuita EXECUTOR SERVICES  Executor lifecycle  Derived from the interface of ExecutorService type 16Riccardo Cardin Running Shutting down Terminated Executors are created in running state. In this state an executor accepts new tasks and schedules them for execution This state is reached after shutdown method was called. No new task are accepted, but previously submitted task are allowed to complete. The shutdownNow method initiates an abrupt shutdown: no queued task not yet begun is started Once all task are completed, the executor transitions to the terminated state
  • 17. Programmazione concorrente e distribuita DEADLOCKS  Multiple threads wait forever due to a cyclic locking dependency  If threads are nodes and relations of dependency are edges, a cyclic graph means to have a deadlock  The JVM cannot detect deadlock, differently from database systems 17Riccardo Cardin A R1 B R2 C R3 Also known as deadly embrace: A needs a resource R hold by B, B a resource hold by C, an so on...
  • 18. Programmazione concorrente e distribuita DEADLOCKS  Deadlocks rarely manifest themeselves immediatly (only in production under heavy load)  Four conditions have to hold simultaneously (Coffman conditions)  Mutual exclusion: at least one resource must be held in a non- shareable mode  Hold and wait: a process is currently holding at least one resource and requesting additional resources  No preemption: a resource can be released only voluntarily  Circular wait: a process must be waiting for a resource which is being held by another process, which in turn is waiting for the first process to release the resource 18Riccardo Cardin
  • 19. Programmazione concorrente e distribuita DEADLOCKS 19Riccardo Cardin
  • 20. Programmazione concorrente e distribuita EXAMPLES 20Riccardo Cardin https://github.com/rcardin/pcd-snippets
  • 21. Programmazione concorrente e distribuita REFERENCES  Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay Horstmann, Gary Cornell, 2012, Prentice Hall  Chap. 6 «Task Execution», Java Concurrency in Practice, Brian Goetz, 2006, Addison-Wesley Professional  Chap. 10 «Avoiding Liveness Hazards», Java Concurrency in Practice, Brian Goetz, 2006, Addison-Wesley Professional  Chap. 10 «Concurrent Programming», Core Java for the Impatient, Cay Horstmann, 2015, Addison-Wesley  Deadlocks https://en.wikipedia.org/wiki/Deadlock 21Riccardo Cardin