SlideShare a Scribd company logo
Threading & the EDT
Threading & the EDT
✦Threading is a difficult subject, even experts can
miss some of the nuance
✦It’s a powerful and crucial tool in building
performant apps
✦Codename One has some unique functionality
related to threading both above and below the
surface
Event Dispatch Thread (EDT)
✦All major OS’s use a single thread to access UI
features
✦That thread is the OS Native Main Thread
✦The EDT hides the existence of that thread
✦This increases portability - OS threads behave
very differently
✦This allows features that don’t exist in the target
platform (e.g. invokeAndBlock)
What’s the EDT?
While
Codename One Is
Running
Paint,
Handle events
& Animations
Sleep if
nothing else is
needed
Almost Everything is on the EDT
✦All paint methods, events and callable code happens
on the EDT
✦ConnectionRequest callbacks happen on the network
thread
✦invokeAndBlock uses it’s own thread
✦The browser component’s navigation listener exposes
the native OS thread (for a special reason)
Why only on the EDT?
✦Our code can make assumptions and avoid
expensive synchronized calls
✦This increases performance and allows us to utilize
threads in a more effective/consistent way
callSerially
© Codename One 2017 all rights reserved
callSerially
✦callSerially adds a runnable element to a list within the
EDT. The run() method will be invoked on the next
EDT loop cycle
public void callSerially(Runnable r){
if(codenameOneRunning) {
synchronized(lock) {
pendingSerialCalls.add(r);
lock.notifyAll();
}
} else {
r.run();
}
}
int size = pendingSerialCalls.size();
if(size > 0) {
Runnable[] array = null;
synchronized(lock) {
size = pendingSerialCalls.size();
array = new Runnable[size];
pendingSerialCalls.toArray(array);
if(size == pendingSerialCalls.size()) {
// this is faster
pendingSerialCalls.clear();
} else {
// this can occur if an element was added during the loop
for(int iter = 0 ; iter < size ; iter++) {
pendingSerialCalls.remove(0);
}
}
}
for(int iter = 0 ; iter < size ; iter++) {
array[iter].run();
}
// after finishing an event cycle there might be serial calls waiting to return
synchronized(lock){
lock.notify();
}
processSerialCalls
int size = pendingSerialCalls.size();
if(size > 0) {
Runnable[] array = null;
synchronized(lock) {
size = pendingSerialCalls.size();
array = new Runnable[size];
pendingSerialCalls.toArray(array);
if(size == pendingSerialCalls.size()) {
// this is faster
pendingSerialCalls.clear();
} else {
// this can occur if an element was added during the loop
for(int iter = 0 ; iter < size ; iter++) {
pendingSerialCalls.remove(0);
}
}
}
for(int iter = 0 ; iter < size ; iter++) {
array[iter].run();
}
// after finishing an event cycle there might be serial calls waiting to return
synchronized(lock){
lock.notify();
}
processSerialCalls
Array Copy
Copy all elements to an array
and remove them otherwise
invokeAndBlock from
within a callSerially() can
cause an infinite loop...
Usage
✦There are two use cases for callSerially
✦If you opened a thread (or were invoked from a
thread) and need to make changes to the UI
✦If you need to postpone an operation to the next cycle
of the EDT
new Thread() {
public void run() {
byte[] data = Util.readToByteArray();
Display.getInstance().callSerially(() -> updateUIWithData(data));
}
}.start();
callSeriallyAndWait
✦callSeriallyAndWait will block until the call serially
completes
public void callSeriallyAndWait(Runnable r){
if(isEdt()) {
throw new RuntimeException("This method MUST NOT be invoked on the EDT");
}
RunnableWrapper c = new RunnableWrapper(r, 0);
callSerially(c);
flushEdt();
synchronized(lock) {
while(!c.isDone()) {
try {
// poll doneness to prevent potential race conditions
lock.wait(50);
} catch(InterruptedException err) {}
}
}
}
Usage
✦It isn’t used as often but makes sense when you need
a result
new Thread() {
public void run() {
downloadFile();
Display.getInstance().callSeriallyAndWait(() -> promptUserForOverwrite());
if(userAgreed) {
overwriteFile();
} else {
createNewFile();
}
}
}.start();
invokeAndBlock
© Codename One 2017 all rights reserved
invokeAndBlock
✦This is probably one of the hardest concepts for
developers to grasp as most frameworks/OS’s don’t
have an equivalent of invokeAndBlock
✦It’s the exact opposite of callSeriallyAndWait
✦invokeAndBlock stops the EDT and winds it manually,
it then opens a new thread and restores the EDT
when that new thread completes
✦invokeAndBlock powers api’s like Dialog,
addToQueueAndWait etc.
Remember This?
While
Codename One Is
Running
Paint,
Handle events
& Animations
Sleep if
nothing else is
needed
This is invoke and block
While
Codename One Is
Running
Paint,
Handle events
& Animations
Sleep if
nothing else is
needed
invokeAndBlock
open new thread
Did the
thread finish
running?
No
Return from
method
Yes
// this class allows a runtime exception to propogate correctly out of the internal thread
RunnableWrapper w = new RunnableWrapper(r, 1);
RunnableWrapper.pushToThreadPool(w);
// loop over the EDT until the thread completes then return
while(!w.isDone() && codenameOneRunning) {
edtLoopImpl();
synchronized(lock){
if(shouldEDTSleep()) {
impl.edtIdle(true);
try {
lock.wait(10);
} catch (InterruptedException ex) {
}
impl.edtIdle(false);
}
}
}
// if the thread threw an exception we need to throw it onwards
if(w.getErr() != null) {
throw w.getErr();
}
invokeAndBlock Implementation
Usage
✦This code would execute on the EDT but allow you to
do intensive things in between
if(!Dialog.show("Do this?", "Are you sure", "Yes", "No")) {
return;
}
Display.getInstance().invokeAndBlock(() -> doLongRunningIOTask());
label.setText("We are nearly there...");
form.revalidate();
Display.getInstance().invokeAndBlock(() -> anotherLongRunningIOTask());
label.setText("Done!");
form.revalidate();
Guidelines
© Codename One 2017 all rights reserved
General Guidelines
✦Don’t block the EDT when possible
✦Opening another thread doesn’t necessarily fix the
problem see https://www.codenameone.com/blog/
performance-true-story.html
✦Intensive operations must yield to keep an app
responsive
✦Some operations (e.g. image manipulation) can work
off the EDT but not on all platforms (e.g. iOS)
Debugging
✦Use the EDT violation
detection tool
✦It can detect “false positives”
and can’t guarantee the
detection of every error but
it’s a good start
What did we learn?
✦Why we have the EDT
✦How we can rely on it and on the fact that our
code is single threaded inherently
✦The difference and importance of callSerially,
callSeriallyAndWait & invokeAndBlock
✦How to detect errors and what we should be
careful of
Thank You

More Related Content

Similar to Threading & the EDT.pdf

Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
creativegamerz00
 
18 concurrency
18   concurrency18   concurrency
18 concurrency
dhrubo kayal
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
Eberhard Wolff
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
Konrad Malawski
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
Francesco Nolano
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
Robert Brown
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
ssuserec53e73
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
kavitamittal18
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
HemantSharma134028
 
4759826-Java-Thread
4759826-Java-Thread4759826-Java-Thread
4759826-Java-Thread
Márcio Antônio Moraes Reyes
 
Thread
ThreadThread
Thread
phanleson
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
hawkowl
 
multithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.pptmultithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.ppt
shikhaverma566116
 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
Robert MacLean
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
João Esperancinha
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
Adil Jafri
 

Similar to Threading & the EDT.pdf (20)

Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
18 concurrency
18   concurrency18   concurrency
18 concurrency
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
4759826-Java-Thread
4759826-Java-Thread4759826-Java-Thread
4759826-Java-Thread
 
Thread
ThreadThread
Thread
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
multithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.pptmultithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.ppt
 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 

More from ShaiAlmog1

The Duck Teaches Learn to debug from the masters. Local to production- kill ...
The Duck Teaches  Learn to debug from the masters. Local to production- kill ...The Duck Teaches  Learn to debug from the masters. Local to production- kill ...
The Duck Teaches Learn to debug from the masters. Local to production- kill ...
ShaiAlmog1
 
create-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdfcreate-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdf
ShaiAlmog1
 
create-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdfcreate-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdfcreate-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdfcreate-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdfcreate-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdf
ShaiAlmog1
 
create-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdfcreate-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdfcreate-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdf
ShaiAlmog1
 
create-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdfcreate-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdf
ShaiAlmog1
 
create-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdfcreate-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdfcreate-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
ShaiAlmog1
 
create-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdfcreate-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdfCreating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdfCreating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdfCreating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdfCreating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdfCreating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdfCreating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdfCreating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdf
ShaiAlmog1
 

More from ShaiAlmog1 (20)

The Duck Teaches Learn to debug from the masters. Local to production- kill ...
The Duck Teaches  Learn to debug from the masters. Local to production- kill ...The Duck Teaches  Learn to debug from the masters. Local to production- kill ...
The Duck Teaches Learn to debug from the masters. Local to production- kill ...
 
create-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdfcreate-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdf
 
create-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdfcreate-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdf
 
create-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdfcreate-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdf
 
create-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdfcreate-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdf
 
create-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdfcreate-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdf
 
create-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdfcreate-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdf
 
create-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdfcreate-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdf
 
create-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdfcreate-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdf
 
create-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdfcreate-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdf
 
create-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdfcreate-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdf
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
 
create-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdfcreate-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdf
 
Creating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdfCreating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdf
 
Creating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdfCreating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdf
 
Creating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdfCreating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdf
 
Creating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdfCreating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdf
 
Creating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdfCreating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdf
 
Creating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdfCreating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdf
 
Creating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdfCreating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdf
 

Recently uploaded

Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 

Threading & the EDT.pdf

  • 2. Threading & the EDT ✦Threading is a difficult subject, even experts can miss some of the nuance ✦It’s a powerful and crucial tool in building performant apps ✦Codename One has some unique functionality related to threading both above and below the surface
  • 3. Event Dispatch Thread (EDT) ✦All major OS’s use a single thread to access UI features ✦That thread is the OS Native Main Thread ✦The EDT hides the existence of that thread ✦This increases portability - OS threads behave very differently ✦This allows features that don’t exist in the target platform (e.g. invokeAndBlock)
  • 4. What’s the EDT? While Codename One Is Running Paint, Handle events & Animations Sleep if nothing else is needed
  • 5. Almost Everything is on the EDT ✦All paint methods, events and callable code happens on the EDT ✦ConnectionRequest callbacks happen on the network thread ✦invokeAndBlock uses it’s own thread ✦The browser component’s navigation listener exposes the native OS thread (for a special reason)
  • 6. Why only on the EDT? ✦Our code can make assumptions and avoid expensive synchronized calls ✦This increases performance and allows us to utilize threads in a more effective/consistent way
  • 7. callSerially © Codename One 2017 all rights reserved
  • 8. callSerially ✦callSerially adds a runnable element to a list within the EDT. The run() method will be invoked on the next EDT loop cycle public void callSerially(Runnable r){ if(codenameOneRunning) { synchronized(lock) { pendingSerialCalls.add(r); lock.notifyAll(); } } else { r.run(); } }
  • 9. int size = pendingSerialCalls.size(); if(size > 0) { Runnable[] array = null; synchronized(lock) { size = pendingSerialCalls.size(); array = new Runnable[size]; pendingSerialCalls.toArray(array); if(size == pendingSerialCalls.size()) { // this is faster pendingSerialCalls.clear(); } else { // this can occur if an element was added during the loop for(int iter = 0 ; iter < size ; iter++) { pendingSerialCalls.remove(0); } } } for(int iter = 0 ; iter < size ; iter++) { array[iter].run(); } // after finishing an event cycle there might be serial calls waiting to return synchronized(lock){ lock.notify(); } processSerialCalls
  • 10. int size = pendingSerialCalls.size(); if(size > 0) { Runnable[] array = null; synchronized(lock) { size = pendingSerialCalls.size(); array = new Runnable[size]; pendingSerialCalls.toArray(array); if(size == pendingSerialCalls.size()) { // this is faster pendingSerialCalls.clear(); } else { // this can occur if an element was added during the loop for(int iter = 0 ; iter < size ; iter++) { pendingSerialCalls.remove(0); } } } for(int iter = 0 ; iter < size ; iter++) { array[iter].run(); } // after finishing an event cycle there might be serial calls waiting to return synchronized(lock){ lock.notify(); } processSerialCalls Array Copy Copy all elements to an array and remove them otherwise invokeAndBlock from within a callSerially() can cause an infinite loop...
  • 11. Usage ✦There are two use cases for callSerially ✦If you opened a thread (or were invoked from a thread) and need to make changes to the UI ✦If you need to postpone an operation to the next cycle of the EDT new Thread() { public void run() { byte[] data = Util.readToByteArray(); Display.getInstance().callSerially(() -> updateUIWithData(data)); } }.start();
  • 12. callSeriallyAndWait ✦callSeriallyAndWait will block until the call serially completes public void callSeriallyAndWait(Runnable r){ if(isEdt()) { throw new RuntimeException("This method MUST NOT be invoked on the EDT"); } RunnableWrapper c = new RunnableWrapper(r, 0); callSerially(c); flushEdt(); synchronized(lock) { while(!c.isDone()) { try { // poll doneness to prevent potential race conditions lock.wait(50); } catch(InterruptedException err) {} } } }
  • 13. Usage ✦It isn’t used as often but makes sense when you need a result new Thread() { public void run() { downloadFile(); Display.getInstance().callSeriallyAndWait(() -> promptUserForOverwrite()); if(userAgreed) { overwriteFile(); } else { createNewFile(); } } }.start();
  • 14. invokeAndBlock © Codename One 2017 all rights reserved
  • 15. invokeAndBlock ✦This is probably one of the hardest concepts for developers to grasp as most frameworks/OS’s don’t have an equivalent of invokeAndBlock ✦It’s the exact opposite of callSeriallyAndWait ✦invokeAndBlock stops the EDT and winds it manually, it then opens a new thread and restores the EDT when that new thread completes ✦invokeAndBlock powers api’s like Dialog, addToQueueAndWait etc.
  • 16. Remember This? While Codename One Is Running Paint, Handle events & Animations Sleep if nothing else is needed
  • 17. This is invoke and block While Codename One Is Running Paint, Handle events & Animations Sleep if nothing else is needed invokeAndBlock open new thread Did the thread finish running? No Return from method Yes
  • 18. // this class allows a runtime exception to propogate correctly out of the internal thread RunnableWrapper w = new RunnableWrapper(r, 1); RunnableWrapper.pushToThreadPool(w); // loop over the EDT until the thread completes then return while(!w.isDone() && codenameOneRunning) { edtLoopImpl(); synchronized(lock){ if(shouldEDTSleep()) { impl.edtIdle(true); try { lock.wait(10); } catch (InterruptedException ex) { } impl.edtIdle(false); } } } // if the thread threw an exception we need to throw it onwards if(w.getErr() != null) { throw w.getErr(); } invokeAndBlock Implementation
  • 19. Usage ✦This code would execute on the EDT but allow you to do intensive things in between if(!Dialog.show("Do this?", "Are you sure", "Yes", "No")) { return; } Display.getInstance().invokeAndBlock(() -> doLongRunningIOTask()); label.setText("We are nearly there..."); form.revalidate(); Display.getInstance().invokeAndBlock(() -> anotherLongRunningIOTask()); label.setText("Done!"); form.revalidate();
  • 20. Guidelines © Codename One 2017 all rights reserved
  • 21. General Guidelines ✦Don’t block the EDT when possible ✦Opening another thread doesn’t necessarily fix the problem see https://www.codenameone.com/blog/ performance-true-story.html ✦Intensive operations must yield to keep an app responsive ✦Some operations (e.g. image manipulation) can work off the EDT but not on all platforms (e.g. iOS)
  • 22. Debugging ✦Use the EDT violation detection tool ✦It can detect “false positives” and can’t guarantee the detection of every error but it’s a good start
  • 23. What did we learn? ✦Why we have the EDT ✦How we can rely on it and on the fact that our code is single threaded inherently ✦The difference and importance of callSerially, callSeriallyAndWait & invokeAndBlock ✦How to detect errors and what we should be careful of