The document discusses advanced Android threading concepts including:
1. The main thread is responsible for UI rendering and user interactions. Blocking it can cause app jank and ANRs.
2. Additional threads can be created using Thread or Runnable classes and started to offload work.
3. The Handler, Looper, and MessageQueue classes provide an asynchronous messaging system for communication between threads without blocking. A Looper dispatches messages that are sent via a Handler.
Presentation describes basic concepts of thread pool such as:
- interacting with queues,
- using pools from Executors class,
- task rejecting
- using ThreadFactory for thread creating
- Future and Callable interfaces,
- basic API
- possibilities for extending
Threads are lightweight processes as the overhead of switching between threads is less
Synchronization allows only one thread to perform an operation on a object at a time.
Synchronization prevent data corruption
Thread Synchronization-The synchronized methods define critical sections.
You will learn the Deadlock Condition in Threads and Syncronization of Threads
Presentation describes basic concepts of thread pool such as:
- interacting with queues,
- using pools from Executors class,
- task rejecting
- using ThreadFactory for thread creating
- Future and Callable interfaces,
- basic API
- possibilities for extending
Threads are lightweight processes as the overhead of switching between threads is less
Synchronization allows only one thread to perform an operation on a object at a time.
Synchronization prevent data corruption
Thread Synchronization-The synchronized methods define critical sections.
You will learn the Deadlock Condition in Threads and Syncronization of Threads
This presentation is about advanced multithreading and concurrency in Java. I have tried my best to explain the concepts with code. Feel free to reach me if you have any questions or concerns.
This talk was given in ilJUG on the 29th of July 2014 and discusses the new Java8 StampedLock class. It compares it to different locking mechanism is Java and shows some insights deduced from a simple benchmark
Java Multi Threading Concept
By N.V.Raja Sekhar Reddy
www.technolamp.co.in
Want more...
Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
This presentation is about advanced multithreading and concurrency in Java. I have tried my best to explain the concepts with code. Feel free to reach me if you have any questions or concerns.
This talk was given in ilJUG on the 29th of July 2014 and discusses the new Java8 StampedLock class. It compares it to different locking mechanism is Java and shows some insights deduced from a simple benchmark
Java Multi Threading Concept
By N.V.Raja Sekhar Reddy
www.technolamp.co.in
Want more...
Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients. AND IT'S TRUE!
In this talk given at JBCNConf 2015 in Barcelona, we will see how we use Netty at Trovit since 2013, what brought to us and how it opened our minds. We will share tips that helped us to learn more about Netty, some performance tricks and all things that worked for us.
Esta charla comprende las lecciones aprendidas convirtiendo la app de Android de Teambox (una app repleta de deuda técnica y con un alto nivel de acoplamiento entre clases), en la versión actual de Redbooth, que intenta cumplir la arquitectura Hexagonal y los principios SOLID. Durante la exposición explicaremos como fuimos desenredando el código paso a paso; como aplicamos por partes los conceptos de la arquitectura hexagonal; como dejamos de lado componentes del framework de Android que dificultaban el mantenimiento de la app; y que errores cometimos, como los solucionamos y como se podrían haber evitado.
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,multithreading in java, java multithreading notes, java multithreading notes,different types of multithreading in Java,multithreading with an example, multithreading in Java
Async task, threads, pools, and executors oh my!Stacy Devino
http://360andev.com/sessions/100-async-task-threads-pools-and-executors/
Frome 360 AnDev conference
There are many ways to use Threads and in the multithreaded world in which we live, it can be confusing when, where, and how to use these functions correctly. Still, that assumes you know what they all mean and how to manipulate them. Novices and Experts welcome as there are many schools of thought, but we will explore them all together.
Don’t worry, we have you covered.
Animated Version : but.ly/asyncThread
All you ever wanted to know about Android Loaders and never dared to ask.
Important: I no longer recommend to use a Loader for "one-shot" actions because it's complicated and has a few side-effects. So I recommend to still use AsyncTasks in that case. You can create an AsyncTask inside a Fragment with setRetainInstance(true) to keep the same AsyncTask instance accross configuration changes, but beware not to update the view or interact with the Activity if the result arrives while the fragment is stopped. If you don't need the result, a static AsyncTask will do the job.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
Worried about document security while sharing them in Salesforce? Fret no more! Here are the top-notch security standards XfilesPro upholds to ensure strong security for your Salesforce documents while sharing with internal or external people.
To learn more, read the blog: https://www.xfilespro.com/how-does-xfilespro-make-document-sharing-secure-and-seamless-in-salesforce/
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
10. ● When blocked - system shows ANR dialog
● Exception on network operations
● Exclusive interaction with the UI
android.os.NetworkOnMainThreadException
19. Cancellation flag
public class MyThread extends Thread {
private boolean mRunning;
@Override
public void run() {
mRunning = true;
while (mRunning) {
// Do some work...
}
}
public void cancel() { mRunning = false; }
}
20. Cancellation flag
public class MyThread extends Thread {
private boolean mRunning;
@Override
public void run() {
mRunning = true;
while (mRunning) {
// Do some work...
}
}
public void cancel() { mRunning = false; }
}
21. Cancellation flag
public class MyThread extends Thread {
private boolean mRunning;
@Override
public void run() {
mRunning = true;
while (mRunning) {
// Do some work...
}
}
public void cancel() { mRunning = false; }
}
22. Stopping a thread
● Return from the run() method.
● Use cancellation flag.
● Call the Thread.interrupt() method.
35. Android Threads communication - Why?
Java threads communication mechanisms holds a blocking
risk. (ex: Pipes)
Interaction between threads in Android usually involves the
main thread.
Android defines it’s own non-blocking thread
communication mechanism.
42. android.os.Looper
● Dispatching messages from its queue to Handlers.
● Only one Looper per thread.
● Keeping its thread alive.
● Thread don’t get a Looper by default.*
54. 1. A Looper is created and attached to a thread.
2. Handler is created.
3. The Handler create a Message.
4. The Handler insert the Message into the Looper queue.
5. The Handler is consuming/executing the message.
Overview
56. 1. A Looper is created and attached to a thread.
2. Handler is created.
3. The Handler create a Message.
4. The Handler insert the Message into the Looper queue.
5. The Handler is consuming/executing the message.
Overview
57. Handler creation
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// do stuff
}
};
mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false; // return true if msg consumed
}
});
//Or...
58. Handler creation
mHandler = new Handler(Looper looper) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// do stuff
}
};
mHandler = new Handler(Looper looper, new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false; // return true if msg consumed
}
});
//Or...
61. 1. A Looper is created and attached to a thread.
2. Handler is created.
3. The Handler create a Message.
4. The Handler insert the Message into the Looper queue.
5. The Handler is consuming the message.
Overview
63. Creating a Message
// Data messages
Message.obtain(Handler h);
Message.obtain(Handler h, int what);
Message.obtain(Handler h, int what, Object o);
Message.obtain(Handler h, int what, int arg1, int arg2);
Message.obtain(Handler h, int what, int arg1, int arg2, Object o);
// Task message
Message.obtain(Handler h, Runnable task);
// Copy constructor
Message.obtain(Message originalMsg);
// Add data Bundle to existing message
msg.setData(Bundle bundle);
64. Creating a Message with Handler
Message msg = handler.obtainMessage(/*...*/);
65. Creating a Message
Message message = Message.obtain(); // Return empty message from pool
message.what = 4;
message.arg1 = 100;
message.arg2 = 200;
message.obj = new Object();
message.setData(bundle);
67. 1. A Looper is created and attached to a thread.
2. Handler is created.
3. The Handler create a Message.
4. The Handler insert the Message into the Looper queue.
5. The Handler is consuming the message.
Overview
69. Inserting data message to the queue
boolean handler.sendMessage(msg);
boolean handler.sendMessageAtFrontOfQueue(msg);
boolean handler.sendMessageDelayed(msg, 2000);
// And more...
70. Inserting task message
boolean handler.post(Runnable r)
boolean handler.postAtFrontOfQueue(Runnable r)
boolean handler.postDelayed(Runnable r, long delayMillis)
// And more...
71. Inserting messages to the queue
// Reference to our Handler
Handler fancyHandler = mFancyThread.getHandler();
// Create data message with what = 1
Message msg = fancyHandler.obtainMessage(1);
// Adding the message to the queue
fancyHandler.sendMessage(msg);
// Adding task message to the queue
fancyHandler.post(new MyRunnable());
73. Removing a Message from the queue
// Remove task message
Handler.removeCallbacks(Runnable r);
// Remove data messages
Handler.removeMessages(int what);
// Remove everything
Handler.removeCallbacksAndMessages(null);
// AND more...
74. 1. A Looper is created and attached to a thread.
2. Handler is created.
3. The Handler create a Message.
4. The Handler insert the Message into the Looper queue.
5. The Handler is consuming the message.
Overview
75. Consuming - Overriding handleMessage()
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
Logger.d("Received message type - 1");
break;
case 2:
Logger.d("Received message type - 2");
break;
}
}
};
76. Consuming - Handler.Callback
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 1:
Logger.d("Received message type - 1");
return true;
case 2:
Logger.d("Received message type - 2");
return true;
default:
return false;
}
}
The Message is handled?
77. Consuming task message
// No extra work is needed.
fancyHandler.post(new Runnable() {
@Override
public void run() {
// Will run on the Handler thread.
}
});
78. Keep it clean!
Don’t forget to call quit()
on your Looper when it is no
longer needed!
82. Looper.quit() VS .quitSafely()
.quit() .quitSafely()
● All pending in the queue, Including
messages ready to be dispatched - are
discarded.
● Looper won’t process new messages.
● Discards only messages that are not
ready to dispatch. Ready messages will
be dispatched.
● Looper won’t process new messages.
● Only from API 18.
85. The Main thread Looper
The Main thread is the only
thread with a Looper by default.
The Looper cannot be stopped.
You can access the Main thread Looper from anywhere
with: Looper.getMainLooper()
86. Main thread Handler creation
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "I'm running on the Main thread.");
}
});
87. Messages passing is a powerful async mechanism
but it can be hard to implement from scratch.
Luckily, You don’t have too...
92. HandlerThread
HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
//Make sure to call start() before creating the Handler!
handlerThread.start();
Handler handler = new Handler(mMyHandlerThread.getLooper());
Accessing the thread Looper
100. IntentService - Example use case
“I want to preload data from my
server to my local DB even
when my app is in the
foreground.”
101. IntentService
● Subclass of Service.
● Executes operation on a background thread.
● Multiple startService() calls function as a work queue.
● Automatically stops when out of work.
104. IntentService
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService"); // This will be the worker thread name
}
@Override
protected void onHandleIntent(Intent intent) {
// Do some work in the background...
}
} Reference to the calling Intent
105. IntentService as a work queue
public class MyIntentService extends IntentService {
public MyIntentService() { super("MyIntentService"); }
public static Intent start(Context context, String name) {
Intent i = new Intent(context, MyIntentService.class);
i.putExtra("extra_name", name);
return i;
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
String name = intent.getStringExtra("extra_name");
for (int i = 1 ; i <= 3 ; i ++) {
Log.d("MyIntentService", name + " counts " + i);
}
}
}
Extracting data from
Intent
Convenient method
to create Intent with
data.
106. IntentService as a work queue
public class MyIntentService extends IntentService {
// …
@Override
public void onCreate() {
super.onCreate();
Logger.d("onCreate() called.”);
}
@Override
public void onDestroy() {
super.onDestroy();
Logger.d("onDestory() called.");
}
}
107. IntentService as a work queue
startService(MyIntentService.start(this, "John"));
startService(MyIntentService.start(this, "Elvis"));
startService(MyIntentService.start(this, "Sara"));
108. Log output
D/Academy: onCreate() called.
D/MyIntentService: John counts 1
D/MyIntentService: John counts 2
D/MyIntentService: John counts 3
D/MyIntentService: Elvis counts 1
D/MyIntentService: Elvis counts 2
D/MyIntentService: Elvis counts 3
D/MyIntentService: Sara counts 1
D/MyIntentService: Sara counts 2
D/MyIntentService: Sara counts 3
D/Academy: onDestory() called.
109. IntentService
Perfect for “fire and forget” long-running operations.
Built-in queue mechanism. Auto stop when work is done.
Is a Service - Less “killable”.
Easy to implement.
Callbacks to UI are complicated. (ResultReceiver)
Cannot cancel.
115. Executing AsyncTask
DownloadImageTask asyncTask = new DownloadImageTask(imageView);
asyncTask.execute(imageUrl);
// If API >= 11:
// or
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imageUrl);
// or
asyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, imageUrl);
// or
asyncTask.executeOnExecutor(myCustomExecutor, imageUrl);
116. Cancelling running AsyncTask
asyncTask.cancel(true);
@Override
protected Integer doInBackground(Void... params) {
int currentCount = 0;
while (currentCount < 10 && !isCancelled()) { // Checking if canceled periodically
currentCount ++;
}
return currentCount;
}
Also interrupt the thread?
117. AsyncTask
Don’t let the abstraction fool you!
If you can - specify executor.
Always use cancel()!
Be vigilant. Avoid memory leaks!
Use only as static inner class or as a stand-alone class.
118. AsyncTask
Useful for quick “in-and-out” operations.
Easy progress and results update on the UI.
Easy to implement.
Easily misused. Handle with caution!
120. Loaders - Example use case
“I’m querying data from a
Content provider.”
121. Loaders
● Can Load data asynchronously.
● Coordinating with Activity lifecycle.
● Surviving configuration changes.
122. Loaders
Loader<D>
The base class of all Loaders.
AsyncTaskLoader<D>
Subclass of Loader<D>, uses AsyncTask to do its
work in the background.
CursorLoader<D>
Subclass of AsyncTaskLoader<Cursor>, built to
query ContentProviders and monitor their data.
142. Pre-defined Executors
// Single thread is executing the tasks in order.
Executors.newSingleThreadExecutor();
// Keeping the number of threads constant.
Executors.newFixedThreadPool(n);
// Dynamic size pool - grows/shrinks as needed.
// with 60 sec idle time per thread.
Executors.newCachedThreadPool();
143. Pre-defined Executors
// Single thread is executing the tasks in order.
Executors.newSingleThreadExecutor(threadFactory);
// Keeping the number of threads constant.
Executors.newFixedThreadPool(n, threadFactory);
// Dynamic size pool - grows/shrinks as needed.
// with 60 sec idle time per thread.
Executors.newCachedThreadPool(threadFactory);
145. MyThreadFactory
public class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(@NonNull Runnable r) {
Thread thread = new Thread(r);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return thread;
}
}
146. Creating custom Executor
Executor executor = new ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
);
147. Creating custom Executor
Executor executor = new ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
);
Minimum number of threads to keep in the pool
148. Creating custom Executor
Executor executor = new ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
);
Maximum number of threads to keep in the pool
149. Creating custom Executor
Executor executor = new ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
);
Time before idle thread is terminated
150. Creating custom Executor
Executor executor = new ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
);
The queue type
151. Creating custom Executor
Executor executor = new ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
);
ThreadFactory for threads creation
152. Creating custom Executor
Executor executor = new ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
);
How to handle rejected task
154. AsyncTask default parallel executor values since Kitkat (API 19)
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating
// the CPU with background work
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
155. Executing a task
mExecutor.execute(new MyRunnableTask());
// When task rejection is possible
try {
mExecutor.execute(new MyRunnableTask());
} catch (RejectedExecutionException e) {
// Handle rejection gracefully
}
162. Remember - Don’t leak!
Avoid non static inner classes when possible.
163. Remember - Don’t leak!
Avoid non static inner classes when possible.
Avoid anonymous class declaration when possible.
164. Remember - Don’t leak!
Avoid non static inner classes when possible.
Avoid anonymous class declaration when possible.
Always implement cancellation policy.
165. Remember - Don’t leak!
Avoid non static inner classes when possible.
Avoid anonymous class declaration when possible.
Always implement cancellation policy.
Always release references.
166. Remember - Don’t leak!
Avoid non static inner classes when possible.
Avoid anonymous class declaration when possible.
Always implement cancellation policy.
Always release references.
Be mindful to components lifecycles.