SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012
Coen De Roover
 

Was ist angesagt? (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
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie Java - Concurrent programming - Thread's advanced concepts

Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
Distributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMIDistributed Objects: CORBA/Java RMI
Distributed Objects: CORBA/Java RMI
elliando dias
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvm
aragozin
 
remote method invocation
remote method invocationremote method invocation
remote method invocation
Arun Nair
 

Ähnlich wie 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
 

Mehr von Riccardo Cardin

Mehr von 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
 

Kürzlich hochgeladen

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Kürzlich hochgeladen (20)

%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
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 🔝✔️✔️
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
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 🔝✔️✔️
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 

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