SlideShare a Scribd company logo
1 of 34
JAVA 8 Parallel Stream
第五組:蔡詠捷、王登文、游憶文
outline
• Java 8 Lambda Expression
• Stream & Parallel Stream
• Code Demo
• Java Fork and Join using ForkJoinPool(Java7)
• Conclusion
Java 8 Lambda Expression
Lambda Expression
• Java 8 support Lambda Expression then officially support functional
programming paradigm
• Lambda comes from the Lambda Calculus and refers to anonymous
functions in programming
• Lambda Expression
• Method argument 必須為一個 Functional Interface
• Functional Interface : Single Abstract Method interface(SAM interface)
• Ex : java.lang.Runnable, java.util.Comparator
Lambda Expression
• Functional Interface 定義:只有一個 public abstract method 的 Java
Interface
• 取代Functional Interface所產出的匿名類別,簡化程式碼
Lambda Expression
• @FunctionalInterface Annotation
Stream
• Stream 是一個Collection Wrapper,可以讓把集合內的元素 ( Elements ) 以
串流 ( Stream ) 形式交到 Stream Methods 以 Lambda Expression 執行
• Stream 執行時期如同 Iterator,單向而不可往返,資料只讀取一次,讀取過一
次後即用盡了
Stream
• Lazy evalutation
• JVM 在沒有遇到 terminal operations 前,並不會執行任何 Stream method
• Short-circuit execution
• JVM 會自行判斷 short-circuit,提早完成集合元素遍歷 ( Element traversal )
• Automatic parallelism
• JVM 可以把 Java Lambda Streams 同時交給多核心處理器 ( Multi-Core )或多線程
(Multi-Thread) 來執行,無須去編寫任何多線程代碼
Stream
• Lazy evaluation
• Code example
Stream
• Short circuit example
• ( fn1() || fn2() )
• if fn1() is true , fn2() will not execute
• ( fn1() && fn2() )
• if fn1() is false , fn2() will not execute
Stream
• Collection support
• Array support
Parallel Stream
• 直接將 Stream() 改為 ParallelStream()
• 要視硬體及JVM配置與JVM負載而定
• 也有可能造成負面作用(Side-effect)
Code Demo
Example Background
https://www.dropbox.com/s/dyx9rpxj53ofyxb/%E8%9E%A2%E5
%B9%95%E6%88%AA%E5%9C%96%202015-11-
01%2000.19.44.png?dl=0
Let’s look some examples~
In Java7, We do that......
https://www.dropbox.com/s/dyx9rpxj53ofyxb/%E8%9E%A2%E5
%B9%95%E6%88%AA%E5%9C%96%202015-11-
01%2000.19.44.png?dl=0
In Java8, We just need!
We can easily change to Parallel
Java Fork and Join using ForkJoinPool
Fork
• each subtask can be executed in parallel by different CPUs, or
different threads on the same CPU.
• The limit for when it makes sense to fork a task into subtasks is
also called a threshold. It is up to each task to decide on a sensible
threshold. It depends very much on the kind of work being done.
Join
Once the subtasks have finished
executing, the task may join (merge) all
the results into one result.
ForkJoinPool
A special thread pool which is designed to work well with
fork-and-join task splitting.
Example:As a parameter to the ForkJoinPool constructor
you pass the indicated level of parallelism you desire.
ForkJoinPool forkJoinPool = new ForkJoinPool(8);
As a parameter to the ForkJoinPool constructor you pass
the indicated level of parallelism you desire.
ForkJoinPool
You can submit two types of tasks. RecursiveAction and
RecursiveTask.
Action won’t return any result, just compute but task will return
something.
ForkJoinPool
You can submit two types of tasks. RecursiveAction and
RecursiveTask.
Action won’t return any result, just compute but task will return
something.
Use case:
MyRecursiveAction myRecursiveAction = new MyRecursiveAction(24);
forkJoinPool.invoke(myRecursiveAction);
Advanced Topic: http://coopsoft.com/ar/CalamityArticle.html
Parallel Stream is good or
not good?
Discuss Parallel Stream Good and Bad
Parallel Stream Problem
• Java 8 parallel streams 也許會讓
程式跑得更快,或者不會,甚至是
跑的更慢
• streams 方法以低成本達到平行處
理(parallel processing)的方便性,
but they do almost in a ‘Black
Box’
• parallel processing 並非等同於
concurrent processing. 但許多在
Java8中「automatic
parallelization」範例 裡事實上都
是concurrent processing.
Concurrent Processing VS Parallel Processing
Streams Good for
• They allow functional
programming style using
bindings.
• They allow for better
performance by removing
iteration. Iteration occurs with
evaluation. With streams, we can
bind dozens of functions without
iterating.
• Streams may be infinite.
Functions may be bound to
infinite streams without problem.
=>a short circuiting operation
And Not Good For
• All streams use the same
ForkJoinPool=>very long
running task=> many long
running sub-tasks => use
each thread in pool
• one parallel subtask
performing I/O has side
effects on others
• Not many threads running at
the same time, and in
particular no other parallel
stream
使用Stream 建議
• 適合使用
• 需在多核心的CPU下執行才能表現效能
• 無I/O存取下
• 切割Pool & Num Setting
• Collection,Array…
• 不適合使用
• 需在單核心的CPU下執行效能差
• I/O存取佔執行之大部份作業下
• 建議:
• 不使用Default ForkJoin Pool(除非在執行作業的Task及伺服器設定可容許…)
結論
• Parallel Stream 看似方便、好處多,但背後有多少問題是我們還沒發現的?
• Parallel streams 是不可預知的,難以最正確的方式在運作.
• 大部份使用Parallel Stream時無法預知可能會影響到正在 運作不相關的程式的
執行效能。
• 在請「parallel Stream」來時,請三思而後行(除非功力深厚OR…)
Reference
• https://dzone.com/articles/think-twice-using-java-8
• http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/
• http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
• https://wefollownews.appspot.com/cittopnews201408_48/14848.html
• http://openhome.cc/Gossip/Java/ParallelStream.html
• http://www.slideshare.net/dgomezg/parallel-streams-en-java-
8http://www.slideshare.net/JustinSDK/java-se-8-lambda
• http://magiclen.org/java-8-lambda/http://developer.51cto.com/art/201311/417451.htm
• Custom Thread Pool 參考 : http://stackoverflow.com/questions/21163108/custom-thread-
pool-in-java-8-parallel-stream
• ForkJoinPool submit, execute, invoke :
http://stackoverflow.com/questions/17881183/difference-between-execute-submit-and-
invoke-in-a-forkjoinpool

More Related Content

What's hot

What's hot (19)

Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Mule java part-1
Mule java part-1Mule java part-1
Mule java part-1
 
Open Source Compiler Construction for the JVM
Open Source Compiler Construction for the JVMOpen Source Compiler Construction for the JVM
Open Source Compiler Construction for the JVM
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java 8 concurrency abstractions
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractions
 
Ruby on the JVM
Ruby on the JVMRuby on the JVM
Ruby on the JVM
 
Java 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureJava 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the future
 
Java 7 & 8
Java 7 & 8Java 7 & 8
Java 7 & 8
 
Load test REST APIs using gatling
Load test REST APIs using gatlingLoad test REST APIs using gatling
Load test REST APIs using gatling
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
Java Batch
Java BatchJava Batch
Java Batch
 
JVM++: The Graal VM
JVM++: The Graal VMJVM++: The Graal VM
JVM++: The Graal VM
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017
 
Web development basics (Part-5)
Web development basics (Part-5)Web development basics (Part-5)
Web development basics (Part-5)
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
Rjb
RjbRjb
Rjb
 
Php 7 - YNS
Php 7 - YNSPhp 7 - YNS
Php 7 - YNS
 
Gatling Tool in Action at Devoxx 2012
Gatling Tool in Action at Devoxx 2012Gatling Tool in Action at Devoxx 2012
Gatling Tool in Action at Devoxx 2012
 
JRuby in Java Projects
JRuby in Java ProjectsJRuby in Java Projects
JRuby in Java Projects
 

Viewers also liked

Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APIcaswenson
 
Java 8-streams-and-parallelism
Java 8-streams-and-parallelismJava 8-streams-and-parallelism
Java 8-streams-and-parallelismDeepak Shevani
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in JavaAyesha Kanwal
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 

Viewers also liked (11)

Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security API
 
Java 8-streams-and-parallelism
Java 8-streams-and-parallelismJava 8-streams-and-parallelism
Java 8-streams-and-parallelism
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 

Similar to Java 8 parallel stream

Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin ProgrammingAtlassian
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick GuideAnton Shchastnyi
 
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)OpenBlend society
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.netJanbask ItTraining
 
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...Vyacheslav Lapin
 
1 Module 1 Introduction.pptx
1 Module 1 Introduction.pptx1 Module 1 Introduction.pptx
1 Module 1 Introduction.pptxBhargaviDalal3
 
AKKA and Scala @ Inneractive
AKKA and Scala @ InneractiveAKKA and Scala @ Inneractive
AKKA and Scala @ InneractiveGal Aviv
 
Clojure and The Robot Apocalypse
Clojure and The Robot ApocalypseClojure and The Robot Apocalypse
Clojure and The Robot Apocalypseelliando dias
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes BackBurke Libbey
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9Gal Marder
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting StartedRakesh Madugula
 
Java Closures
Java ClosuresJava Closures
Java ClosuresBen Evans
 

Similar to Java 8 parallel stream (20)

Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin Programming
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick Guide
 
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.net
 
Java 8
Java 8Java 8
Java 8
 
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
 
Panama.pdf
Panama.pdfPanama.pdf
Panama.pdf
 
1 Module 1 Introduction.pptx
1 Module 1 Introduction.pptx1 Module 1 Introduction.pptx
1 Module 1 Introduction.pptx
 
AKKA and Scala @ Inneractive
AKKA and Scala @ InneractiveAKKA and Scala @ Inneractive
AKKA and Scala @ Inneractive
 
Clojure and The Robot Apocalypse
Clojure and The Robot ApocalypseClojure and The Robot Apocalypse
Clojure and The Robot Apocalypse
 
Java introduction
Java introductionJava introduction
Java introduction
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes Back
 
What’s expected in Java 9
What’s expected in Java 9What’s expected in Java 9
What’s expected in Java 9
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
Java programming and security
Java programming and securityJava programming and security
Java programming and security
 

Recently uploaded

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
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
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%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 Hararemasabamasaba
 
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
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
%+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
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 

Recently uploaded (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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 🔝✔️✔️
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%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
 
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 🔝✔️✔️
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
%+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...
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 

Java 8 parallel stream

  • 1. JAVA 8 Parallel Stream 第五組:蔡詠捷、王登文、游憶文
  • 2. outline • Java 8 Lambda Expression • Stream & Parallel Stream • Code Demo • Java Fork and Join using ForkJoinPool(Java7) • Conclusion
  • 3. Java 8 Lambda Expression
  • 4.
  • 5. Lambda Expression • Java 8 support Lambda Expression then officially support functional programming paradigm • Lambda comes from the Lambda Calculus and refers to anonymous functions in programming • Lambda Expression • Method argument 必須為一個 Functional Interface • Functional Interface : Single Abstract Method interface(SAM interface) • Ex : java.lang.Runnable, java.util.Comparator
  • 6.
  • 7. Lambda Expression • Functional Interface 定義:只有一個 public abstract method 的 Java Interface • 取代Functional Interface所產出的匿名類別,簡化程式碼
  • 9. Stream • Stream 是一個Collection Wrapper,可以讓把集合內的元素 ( Elements ) 以 串流 ( Stream ) 形式交到 Stream Methods 以 Lambda Expression 執行 • Stream 執行時期如同 Iterator,單向而不可往返,資料只讀取一次,讀取過一 次後即用盡了
  • 10. Stream • Lazy evalutation • JVM 在沒有遇到 terminal operations 前,並不會執行任何 Stream method • Short-circuit execution • JVM 會自行判斷 short-circuit,提早完成集合元素遍歷 ( Element traversal ) • Automatic parallelism • JVM 可以把 Java Lambda Streams 同時交給多核心處理器 ( Multi-Core )或多線程 (Multi-Thread) 來執行,無須去編寫任何多線程代碼
  • 12. Stream • Short circuit example • ( fn1() || fn2() ) • if fn1() is true , fn2() will not execute • ( fn1() && fn2() ) • if fn1() is false , fn2() will not execute
  • 14. Parallel Stream • 直接將 Stream() 改為 ParallelStream() • 要視硬體及JVM配置與JVM負載而定 • 也有可能造成負面作用(Side-effect)
  • 17. Let’s look some examples~ In Java7, We do that...... https://www.dropbox.com/s/dyx9rpxj53ofyxb/%E8%9E%A2%E5 %B9%95%E6%88%AA%E5%9C%96%202015-11- 01%2000.19.44.png?dl=0
  • 18. In Java8, We just need!
  • 19. We can easily change to Parallel
  • 20. Java Fork and Join using ForkJoinPool
  • 21. Fork • each subtask can be executed in parallel by different CPUs, or different threads on the same CPU. • The limit for when it makes sense to fork a task into subtasks is also called a threshold. It is up to each task to decide on a sensible threshold. It depends very much on the kind of work being done.
  • 22. Join Once the subtasks have finished executing, the task may join (merge) all the results into one result.
  • 23. ForkJoinPool A special thread pool which is designed to work well with fork-and-join task splitting. Example:As a parameter to the ForkJoinPool constructor you pass the indicated level of parallelism you desire. ForkJoinPool forkJoinPool = new ForkJoinPool(8); As a parameter to the ForkJoinPool constructor you pass the indicated level of parallelism you desire.
  • 24. ForkJoinPool You can submit two types of tasks. RecursiveAction and RecursiveTask. Action won’t return any result, just compute but task will return something.
  • 25. ForkJoinPool You can submit two types of tasks. RecursiveAction and RecursiveTask. Action won’t return any result, just compute but task will return something.
  • 26. Use case: MyRecursiveAction myRecursiveAction = new MyRecursiveAction(24); forkJoinPool.invoke(myRecursiveAction); Advanced Topic: http://coopsoft.com/ar/CalamityArticle.html
  • 27. Parallel Stream is good or not good? Discuss Parallel Stream Good and Bad
  • 28. Parallel Stream Problem • Java 8 parallel streams 也許會讓 程式跑得更快,或者不會,甚至是 跑的更慢 • streams 方法以低成本達到平行處 理(parallel processing)的方便性, but they do almost in a ‘Black Box’ • parallel processing 並非等同於 concurrent processing. 但許多在 Java8中「automatic parallelization」範例 裡事實上都 是concurrent processing.
  • 29. Concurrent Processing VS Parallel Processing
  • 30. Streams Good for • They allow functional programming style using bindings. • They allow for better performance by removing iteration. Iteration occurs with evaluation. With streams, we can bind dozens of functions without iterating. • Streams may be infinite. Functions may be bound to infinite streams without problem. =>a short circuiting operation
  • 31. And Not Good For • All streams use the same ForkJoinPool=>very long running task=> many long running sub-tasks => use each thread in pool • one parallel subtask performing I/O has side effects on others • Not many threads running at the same time, and in particular no other parallel stream
  • 32. 使用Stream 建議 • 適合使用 • 需在多核心的CPU下執行才能表現效能 • 無I/O存取下 • 切割Pool & Num Setting • Collection,Array… • 不適合使用 • 需在單核心的CPU下執行效能差 • I/O存取佔執行之大部份作業下 • 建議: • 不使用Default ForkJoin Pool(除非在執行作業的Task及伺服器設定可容許…)
  • 33. 結論 • Parallel Stream 看似方便、好處多,但背後有多少問題是我們還沒發現的? • Parallel streams 是不可預知的,難以最正確的方式在運作. • 大部份使用Parallel Stream時無法預知可能會影響到正在 運作不相關的程式的 執行效能。 • 在請「parallel Stream」來時,請三思而後行(除非功力深厚OR…)
  • 34. Reference • https://dzone.com/articles/think-twice-using-java-8 • http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/ • http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ • https://wefollownews.appspot.com/cittopnews201408_48/14848.html • http://openhome.cc/Gossip/Java/ParallelStream.html • http://www.slideshare.net/dgomezg/parallel-streams-en-java- 8http://www.slideshare.net/JustinSDK/java-se-8-lambda • http://magiclen.org/java-8-lambda/http://developer.51cto.com/art/201311/417451.htm • Custom Thread Pool 參考 : http://stackoverflow.com/questions/21163108/custom-thread- pool-in-java-8-parallel-stream • ForkJoinPool submit, execute, invoke : http://stackoverflow.com/questions/17881183/difference-between-execute-submit-and- invoke-in-a-forkjoinpool