SlideShare a Scribd company logo
1 of 24
1
Industrial IoT | Digital Transformation | Industry 4.0
Ramith Jayasinghe
CEO, Co-Founder
E: Jayasinghe@Xiges.io | Blog: https://medium.com/@ramithj
Why Concurrency is hard ?
2
What We are going to discuss…
● Concurrency Coursework – Recap ?
● Common Perceptions / Observations
● Best Practices
3
Concurrency – Recap?
● What's Concurrency/Parallelism?
○ Doing multiple tasks simultaneously. If there are multiple processors/computers, its truly
parallel.
● Thread ? Thread Groups? Thread States?
○ A (simultaneously) running task(s) with in a application. Logically grouped for convenience
(from a programmer’s prospective). Thread states can help when debugging (+ framework
development)
● Race Conditions ? Mutual Exclusion ?
○ Undesired effect of due to concurrent execution. Outcome depends on speed / timing.
○ There got to be a critical-section which screws up the whole thing !
○ Make sure only one thread can execute the critical section at a time.
4
Concurrency – Recap?
● Locks ? Barriers ?
○ Locks are a mechanism to enable mutual exclusion.
○ Barriers are a mechanism to coordinate between set of threads. So all threads needs to wait
until others reach the barrier to proceed.
● Dead Locks ?
○ Program cannot make progress. Threads involved in dead lock are in a ‘circular wait’ on
others due to mutual exclusion and no preemption
5
Concurrency – Recap?
● Starvation ?
○ Happens due to mutual exclusion or due to how scheduling algorithm works.
○ Thread/Process don’t have access to required resources to make progress.
● Atomic Variables ?
○ Implements compare and swap schematics for memory/variables.
○ Atomically read/write shared variables.
6
Concurrency – Recap?
● ThreadLocal Variables ?
○ Each thread is its own version/copy of the variable.
○ Particular thread can’t see other thread’s value.
● Runnable ? Callable ? Futures ?
○ Runnable – (in java) an frequently implemented interface to specify work that needs to
happen concurrently. Doesn’t return a value after the work is completed.
○ Callable – same as Runnable. But allows programmer to return a value.
○ Future – provides a means retrieve the result of a completed callable.
7
Reality
● Most of us will forget most of these in couple of weeks/months 
● If you are in to J2EE/ .NET /JavaScripts you will not deal with most of these
constructs.
● Concurrency is managed by Application Servers/Frameworks.
○ Simple / Component-based programming models (Beans, Servlets, Controllers etc).
○ Load balancing (Local/Cluster-wide) / Automatic, Bean-Managed Concurrency
○ Resource Management
● Most (= ~ 90 % ) of us just move data around:
○ Get Data  Transform  Show in GUI and/or put into a storage.
8
Concurrency: Why is it difficult?
“Too many programmers writing multithreaded programs are like Mickey
Mouse in The Sorcerer's Apprentice. They learn to create a bunch of threads and
get them mostly working, but then the threads go completely out of control and
the programmer doesn't know what to do.”
Source : https://smartbear.com/blog/test-and-monitor/why-johnny-cant-write-
multithreaded-programs/
9
Concurrency: Why is it difficult?
● There is a gap between with examples in text books and
real-world concurrent/distributed applications.
● Programmers don’t understand/care for best practices.
● Applying text book, intro-level content (or cut-n-paste from
web) to solve the problem at hand.
10
Concurrency: Why is it difficult?
● Problems pop-up  Introduce ‘smart solutions’ [= hacks]
to remedy the issues.
● Result is:
○ Poor application performance / Stability.
○ Nobody understands the code.
○ Lots of sleepless nights / cursing !
○ Time / Money wasted.
11
Concurrency: Why is it difficult?
Rule #1
With or With-out Concurrency.
Global Mutable State is bad !
Note: Anything is mutable if its state changes over
time, immutable otherwise.
java.lang.String,
java.time.LocalDate
java.lang.StringBuilder
java.util.Date
class Foo {
private final String state;
public Foo(final String initialValue) {
this.state = initialValue;
}
public String getState() {
return this.state;
}
}
Concurrency: Why is it difficult?
● Examples of Goble State?
○ Global static variables, static classes with public instance variables.
○ Environment Variables, Configurations.
○ Singleton Objects
● Why is it bad?
○ No control over state changes.
○ Very hard to predict / determine program’s state at a given time.
12
What should be the approach?
● If you are using an application server adhere to it’s programming model !
● There is no such a thing as zero global state [ In real life].
● However try to minimize it. How?
○ Define components/layers in the application correctly.
○ Figure out how to how the communication/coordination works for each layer/component.
○ Threading architecture is not thing you will figure-out/design later !
13
What should be the approach?
● Use a threading framework, than creating threads/locks/synchronizations
manually.
○ Thread Pools/Executor Frameworks, Disruptors, Reactive Programming
● Consider what application does:
○ Compute Heavy / IO Heavy
○ Where its going to run on, Load requirements
○ Data Access Patterns
○ Error Handling / Tracing / Debugging.
14
15
Concurrency Programming Models
● Threads + Locks
● Threads + Queues
● Thread Pools / Executors
● Futures, Callbacks
● Reactive Streams, Disruptors
● Etc.
For a good comparison refer: [Concurrency – The good, the bad, the ugly]
https://www.youtube.com/watch?v=OJfS7K-Vkgk
16
Concurrency: Best Practices
● Prefer local variables where possible. Reduce the use of public variables.
● If you are using collections, at least synchronize them. Its wise use concurrent
collections.
● Minimize locking scope:
○ Don’t misuse synchronized methods, blocks. Prefer synchronized blocks over methods.
○ More synchronization means your program performance may suffer.
e.g. Collections.synchronizedList(…), java.util.concurrent.ConcurrentHashMap
17
Concurrency: Best Practices
● Consider using atomic variables. These implement compare-and-swap (CAS)
instructions. On modern processors supports these at hardware level.
e.g. java.util.concurrent.atomic.AtomicInteger:
boolean compareAndSet(int expect, int update)
AtomicInteger atomicInt = new AtomicInteger(4);
Atomic.compareAndSet(5, 0); // if the current value is 5 then set it to 0.
18
Concurrency: Best Practices
● Think twice before creating a thread. Prefer Thread Pools / Executors instead
○ Creating threads are expensive.
○ Requires lots of boiler plate code. ( - Let’s not re-invent the wheel !)
○ Likely to be error prone.
e.g. Thread thread = new Thread(runnable); //why would you do this?
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(runnable); // <- when you can do this.
19
Concurrency: Best Practices
● Work with higher level concurrency control constructs. You don’t need to deal
with Object.wait() and Object.notify().
● Most of the time concurrency requirements you will encounter would be
consumer-producer. Use a subclass of java.util.concurrent.BlockingQueue.
● If you are doing something funky, consider using:
○ LMax Disruptor – Solves performance problems in JDK concurrent framework/collections.
○ RxJava/ Akka.io / Spring Reactor - More higher-level abstractions for data intensive
applications.
○ Netty.io – A framework for developing high throughput network applications
20
Conclusion
● Dealing with concurrency is hard when:
○ Lack of ‘working knowledge’
○ Best practices not followed.
● Adhere to server/framework’s preferred way of doing it.
● Prefer higher-level abstractions.
● Designing/choosing the concurrency scheme upfront is important.
● Be careful not to have too much of ‘global mutable state’
21
References
● https://smartbear.com/blog/test-and-monitor/why-johnny-cant-write-multithreaded-programs/
● https://towardsdatascience.com/is-concurrency-really-increases-the-performance-8cd06dd762f6
● https://www.quora.com/What-are-some-good-and-bad-use-cases-for-concurrency-models-like-
threading-actors-and-STM-Software-Transactional-Memory-When-should-I-choose-one-over-the-
other
● https://joearms.github.io/published/2016-01-26-The-Unintentional-Side-Effects-of-a-Bad-
Concurrency-Model.html
● Concurrency – The good, the bad, the ugly - https://www.youtube.com/watch?v=OJfS7K-Vkgk
● https://javarevisited.blogspot.com/2015/05/top-10-java-multithreading-and.html
● https://www.youtube.com/watch?v=OJfS7K-Vkgk
Thank You !
23
Exercise #1 – Detecting a Deadlock
● It’s a (Black) Friday night. You are in the application support duty roaster !!!
● Suddenly you are getting a loads of entries (in Splunk) :
connection timeouts when invoking order management service.
● Customers can’t place orders  Business is loosing money  Your lead is
freaking out  Pressure is building !!!
● How are you going to figure out what’s going on ?
Reference: https://dzone.com/articles/how-analyze-java-thread-dumps
24
Exercise #2 – Find which thread is spinning
● It’s a (Black) Friday night. You are in the application support duty roaster !!!
● Suddenly you are getting a loads of entries (in Splunk) :
connection timeouts when invoking package management service.
● Customers can’t place orders  Business is loosing money  Your lead is
freaking out  Pressure is building !!!
● How are you going to figure out what’s going on ?

More Related Content

What's hot

The working architecture of node js applications open tech week javascript ...
The working architecture of node js applications   open tech week javascript ...The working architecture of node js applications   open tech week javascript ...
The working architecture of node js applications open tech week javascript ...Viktor Turskyi
 
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Codemotion
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsShashank L
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter KitMark Papis
 
Android Frameworks: Highlighting the Need for a Solid Development Framework 
Android Frameworks: Highlighting the Need for a Solid Development Framework Android Frameworks: Highlighting the Need for a Solid Development Framework 
Android Frameworks: Highlighting the Need for a Solid Development Framework Mutual Mobile
 
Understanding concurrency
Understanding concurrencyUnderstanding concurrency
Understanding concurrencyAnshul Sharma
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyfbenault
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 

What's hot (12)

Thinking Functionally
Thinking FunctionallyThinking Functionally
Thinking Functionally
 
The working architecture of node js applications open tech week javascript ...
The working architecture of node js applications   open tech week javascript ...The working architecture of node js applications   open tech week javascript ...
The working architecture of node js applications open tech week javascript ...
 
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
Mario Fusco - Comparing different concurrency models on the JVM | Codemotion ...
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
 
Android Frameworks: Highlighting the Need for a Solid Development Framework 
Android Frameworks: Highlighting the Need for a Solid Development Framework Android Frameworks: Highlighting the Need for a Solid Development Framework 
Android Frameworks: Highlighting the Need for a Solid Development Framework 
 
Understanding concurrency
Understanding concurrencyUnderstanding concurrency
Understanding concurrency
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 

Similar to Concurrency - Why it's hard ?

Daniel Steigerwald - Este.js - konec velkého Schizma
Daniel Steigerwald - Este.js - konec velkého SchizmaDaniel Steigerwald - Este.js - konec velkého Schizma
Daniel Steigerwald - Este.js - konec velkého SchizmaDevelcz
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfjexp
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaLakshmi Narasimhan
 
Ratpack the story so far
Ratpack the story so farRatpack the story so far
Ratpack the story so farPhill Barber
 
Flux architecture and Redux - theory, context and practice
Flux architecture and Redux - theory, context and practiceFlux architecture and Redux - theory, context and practice
Flux architecture and Redux - theory, context and practiceJakub Kocikowski
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in PythonRyan Johnson
 
Effects, Coeffects & Subscriptions: a pit of success for SPAs
Effects, Coeffects & Subscriptions: a pit of success for SPAsEffects, Coeffects & Subscriptions: a pit of success for SPAs
Effects, Coeffects & Subscriptions: a pit of success for SPAsManuel Rivero
 
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020OdessaJS Conf
 
Effects, coeffects & subscriptions: a pit of success for SPAs Socracan18
Effects, coeffects & subscriptions: a pit of success for SPAs Socracan18Effects, coeffects & subscriptions: a pit of success for SPAs Socracan18
Effects, coeffects & subscriptions: a pit of success for SPAs Socracan18Manuel Rivero
 
Performance Test Automation With Gatling
Performance Test Automation  With GatlingPerformance Test Automation  With Gatling
Performance Test Automation With GatlingKnoldus Inc.
 
BISSA: Empowering Web gadget Communication with Tuple Spaces
BISSA: Empowering Web gadget Communication with Tuple SpacesBISSA: Empowering Web gadget Communication with Tuple Spaces
BISSA: Empowering Web gadget Communication with Tuple SpacesSrinath Perera
 
Meetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaCMeetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaCDamienCarpy
 

Similar to Concurrency - Why it's hard ? (20)

Making Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF UsableMaking Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF Usable
 
Daniel Steigerwald - Este.js - konec velkého Schizma
Daniel Steigerwald - Este.js - konec velkého SchizmaDaniel Steigerwald - Este.js - konec velkého Schizma
Daniel Steigerwald - Este.js - konec velkého Schizma
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdf
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Ratpack the story so far
Ratpack the story so farRatpack the story so far
Ratpack the story so far
 
Flux architecture and Redux - theory, context and practice
Flux architecture and Redux - theory, context and practiceFlux architecture and Redux - theory, context and practice
Flux architecture and Redux - theory, context and practice
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in Python
 
Effects, Coeffects & Subscriptions: a pit of success for SPAs
Effects, Coeffects & Subscriptions: a pit of success for SPAsEffects, Coeffects & Subscriptions: a pit of success for SPAs
Effects, Coeffects & Subscriptions: a pit of success for SPAs
 
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
 
Effects, coeffects & subscriptions: a pit of success for SPAs Socracan18
Effects, coeffects & subscriptions: a pit of success for SPAs Socracan18Effects, coeffects & subscriptions: a pit of success for SPAs Socracan18
Effects, coeffects & subscriptions: a pit of success for SPAs Socracan18
 
Java under the hood
Java under the hoodJava under the hood
Java under the hood
 
Gatling
Gatling Gatling
Gatling
 
Performance Test Automation With Gatling
Performance Test Automation  With GatlingPerformance Test Automation  With Gatling
Performance Test Automation With Gatling
 
Better java with design
Better java with designBetter java with design
Better java with design
 
BISSA: Empowering Web gadget Communication with Tuple Spaces
BISSA: Empowering Web gadget Communication with Tuple SpacesBISSA: Empowering Web gadget Communication with Tuple Spaces
BISSA: Empowering Web gadget Communication with Tuple Spaces
 
Meetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaCMeetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaC
 
JavaFX in Action Part I
JavaFX in Action Part IJavaFX in Action Part I
JavaFX in Action Part I
 
RxSwift
RxSwiftRxSwift
RxSwift
 
Gatling
GatlingGatling
Gatling
 
Akka (1)
Akka (1)Akka (1)
Akka (1)
 

Recently uploaded

New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Concurrency - Why it's hard ?

  • 1. 1 Industrial IoT | Digital Transformation | Industry 4.0 Ramith Jayasinghe CEO, Co-Founder E: Jayasinghe@Xiges.io | Blog: https://medium.com/@ramithj Why Concurrency is hard ?
  • 2. 2 What We are going to discuss… ● Concurrency Coursework – Recap ? ● Common Perceptions / Observations ● Best Practices
  • 3. 3 Concurrency – Recap? ● What's Concurrency/Parallelism? ○ Doing multiple tasks simultaneously. If there are multiple processors/computers, its truly parallel. ● Thread ? Thread Groups? Thread States? ○ A (simultaneously) running task(s) with in a application. Logically grouped for convenience (from a programmer’s prospective). Thread states can help when debugging (+ framework development) ● Race Conditions ? Mutual Exclusion ? ○ Undesired effect of due to concurrent execution. Outcome depends on speed / timing. ○ There got to be a critical-section which screws up the whole thing ! ○ Make sure only one thread can execute the critical section at a time.
  • 4. 4 Concurrency – Recap? ● Locks ? Barriers ? ○ Locks are a mechanism to enable mutual exclusion. ○ Barriers are a mechanism to coordinate between set of threads. So all threads needs to wait until others reach the barrier to proceed. ● Dead Locks ? ○ Program cannot make progress. Threads involved in dead lock are in a ‘circular wait’ on others due to mutual exclusion and no preemption
  • 5. 5 Concurrency – Recap? ● Starvation ? ○ Happens due to mutual exclusion or due to how scheduling algorithm works. ○ Thread/Process don’t have access to required resources to make progress. ● Atomic Variables ? ○ Implements compare and swap schematics for memory/variables. ○ Atomically read/write shared variables.
  • 6. 6 Concurrency – Recap? ● ThreadLocal Variables ? ○ Each thread is its own version/copy of the variable. ○ Particular thread can’t see other thread’s value. ● Runnable ? Callable ? Futures ? ○ Runnable – (in java) an frequently implemented interface to specify work that needs to happen concurrently. Doesn’t return a value after the work is completed. ○ Callable – same as Runnable. But allows programmer to return a value. ○ Future – provides a means retrieve the result of a completed callable.
  • 7. 7 Reality ● Most of us will forget most of these in couple of weeks/months  ● If you are in to J2EE/ .NET /JavaScripts you will not deal with most of these constructs. ● Concurrency is managed by Application Servers/Frameworks. ○ Simple / Component-based programming models (Beans, Servlets, Controllers etc). ○ Load balancing (Local/Cluster-wide) / Automatic, Bean-Managed Concurrency ○ Resource Management ● Most (= ~ 90 % ) of us just move data around: ○ Get Data  Transform  Show in GUI and/or put into a storage.
  • 8. 8 Concurrency: Why is it difficult? “Too many programmers writing multithreaded programs are like Mickey Mouse in The Sorcerer's Apprentice. They learn to create a bunch of threads and get them mostly working, but then the threads go completely out of control and the programmer doesn't know what to do.” Source : https://smartbear.com/blog/test-and-monitor/why-johnny-cant-write- multithreaded-programs/
  • 9. 9 Concurrency: Why is it difficult? ● There is a gap between with examples in text books and real-world concurrent/distributed applications. ● Programmers don’t understand/care for best practices. ● Applying text book, intro-level content (or cut-n-paste from web) to solve the problem at hand.
  • 10. 10 Concurrency: Why is it difficult? ● Problems pop-up  Introduce ‘smart solutions’ [= hacks] to remedy the issues. ● Result is: ○ Poor application performance / Stability. ○ Nobody understands the code. ○ Lots of sleepless nights / cursing ! ○ Time / Money wasted.
  • 11. 11 Concurrency: Why is it difficult? Rule #1 With or With-out Concurrency. Global Mutable State is bad ! Note: Anything is mutable if its state changes over time, immutable otherwise. java.lang.String, java.time.LocalDate java.lang.StringBuilder java.util.Date class Foo { private final String state; public Foo(final String initialValue) { this.state = initialValue; } public String getState() { return this.state; } }
  • 12. Concurrency: Why is it difficult? ● Examples of Goble State? ○ Global static variables, static classes with public instance variables. ○ Environment Variables, Configurations. ○ Singleton Objects ● Why is it bad? ○ No control over state changes. ○ Very hard to predict / determine program’s state at a given time. 12
  • 13. What should be the approach? ● If you are using an application server adhere to it’s programming model ! ● There is no such a thing as zero global state [ In real life]. ● However try to minimize it. How? ○ Define components/layers in the application correctly. ○ Figure out how to how the communication/coordination works for each layer/component. ○ Threading architecture is not thing you will figure-out/design later ! 13
  • 14. What should be the approach? ● Use a threading framework, than creating threads/locks/synchronizations manually. ○ Thread Pools/Executor Frameworks, Disruptors, Reactive Programming ● Consider what application does: ○ Compute Heavy / IO Heavy ○ Where its going to run on, Load requirements ○ Data Access Patterns ○ Error Handling / Tracing / Debugging. 14
  • 15. 15 Concurrency Programming Models ● Threads + Locks ● Threads + Queues ● Thread Pools / Executors ● Futures, Callbacks ● Reactive Streams, Disruptors ● Etc. For a good comparison refer: [Concurrency – The good, the bad, the ugly] https://www.youtube.com/watch?v=OJfS7K-Vkgk
  • 16. 16 Concurrency: Best Practices ● Prefer local variables where possible. Reduce the use of public variables. ● If you are using collections, at least synchronize them. Its wise use concurrent collections. ● Minimize locking scope: ○ Don’t misuse synchronized methods, blocks. Prefer synchronized blocks over methods. ○ More synchronization means your program performance may suffer. e.g. Collections.synchronizedList(…), java.util.concurrent.ConcurrentHashMap
  • 17. 17 Concurrency: Best Practices ● Consider using atomic variables. These implement compare-and-swap (CAS) instructions. On modern processors supports these at hardware level. e.g. java.util.concurrent.atomic.AtomicInteger: boolean compareAndSet(int expect, int update) AtomicInteger atomicInt = new AtomicInteger(4); Atomic.compareAndSet(5, 0); // if the current value is 5 then set it to 0.
  • 18. 18 Concurrency: Best Practices ● Think twice before creating a thread. Prefer Thread Pools / Executors instead ○ Creating threads are expensive. ○ Requires lots of boiler plate code. ( - Let’s not re-invent the wheel !) ○ Likely to be error prone. e.g. Thread thread = new Thread(runnable); //why would you do this? ExecutorService executor = Executors.newCachedThreadPool(); executor.submit(runnable); // <- when you can do this.
  • 19. 19 Concurrency: Best Practices ● Work with higher level concurrency control constructs. You don’t need to deal with Object.wait() and Object.notify(). ● Most of the time concurrency requirements you will encounter would be consumer-producer. Use a subclass of java.util.concurrent.BlockingQueue. ● If you are doing something funky, consider using: ○ LMax Disruptor – Solves performance problems in JDK concurrent framework/collections. ○ RxJava/ Akka.io / Spring Reactor - More higher-level abstractions for data intensive applications. ○ Netty.io – A framework for developing high throughput network applications
  • 20. 20 Conclusion ● Dealing with concurrency is hard when: ○ Lack of ‘working knowledge’ ○ Best practices not followed. ● Adhere to server/framework’s preferred way of doing it. ● Prefer higher-level abstractions. ● Designing/choosing the concurrency scheme upfront is important. ● Be careful not to have too much of ‘global mutable state’
  • 21. 21 References ● https://smartbear.com/blog/test-and-monitor/why-johnny-cant-write-multithreaded-programs/ ● https://towardsdatascience.com/is-concurrency-really-increases-the-performance-8cd06dd762f6 ● https://www.quora.com/What-are-some-good-and-bad-use-cases-for-concurrency-models-like- threading-actors-and-STM-Software-Transactional-Memory-When-should-I-choose-one-over-the- other ● https://joearms.github.io/published/2016-01-26-The-Unintentional-Side-Effects-of-a-Bad- Concurrency-Model.html ● Concurrency – The good, the bad, the ugly - https://www.youtube.com/watch?v=OJfS7K-Vkgk ● https://javarevisited.blogspot.com/2015/05/top-10-java-multithreading-and.html ● https://www.youtube.com/watch?v=OJfS7K-Vkgk
  • 23. 23 Exercise #1 – Detecting a Deadlock ● It’s a (Black) Friday night. You are in the application support duty roaster !!! ● Suddenly you are getting a loads of entries (in Splunk) : connection timeouts when invoking order management service. ● Customers can’t place orders  Business is loosing money  Your lead is freaking out  Pressure is building !!! ● How are you going to figure out what’s going on ? Reference: https://dzone.com/articles/how-analyze-java-thread-dumps
  • 24. 24 Exercise #2 – Find which thread is spinning ● It’s a (Black) Friday night. You are in the application support duty roaster !!! ● Suddenly you are getting a loads of entries (in Splunk) : connection timeouts when invoking package management service. ● Customers can’t place orders  Business is loosing money  Your lead is freaking out  Pressure is building !!! ● How are you going to figure out what’s going on ?