Android Thread based interview questions and answers

Thread:

How will you terminate an alive thread?

There is no direct way to terminate a thread but using the two following ways it can be done. 

  1. Calling ‘interrupt()’ method on the thread object (e.g. threadObj), this will throw an InterruptedException inside the run method of thread. This exception will indicate that we should release the resources gracefully and then exiting the ‘run’ method of thread will terminate the thread.
  2. In case if the InterruptedException is swallowed by the code or ignored as well as If inside the thread’s ‘run’ method if any looping is there, if yes then adding a method check in that loop that if this thread should exit now or not, is done by checking ‘Thread.currentThread().isInterrupted()’ that returns true and then exit the run method
WHAT IS A THREAD POOL?
A Thread pool is a collection of managed threads usually organized in a queue, which execute the tasks in the task queue. Creating a new thread object every time you need
something to be executed asynchronously is expensive. In a thread pool you would just add the tasks you wish to be executed asynchronously to the task queue and the thread pool takes care of assigning an available thread, if any, for the corresponding task. As
soon as the task is completed, the now available thread requests another task (assuming
there is any left). Thread pool helps you avoid creating or destroying more threads, than would really be necessary.

AsyncTask:

Difference between AsyncTasks & Threads?

  • Thread should be used to separate long running operations from main thread so that performance is improved. But it can’t be cancelled elegantly and it can’t handle configuration changes of Android. You can’t update UI from Thread.
  • AsyncTask can be used to handle work items shorter than 5ms in duration. With AsyncTask, you can update UI unlike java Thread. But many long running tasks will choke the performance.
  • The main difference is about the way they are triggered. A Thread can be triggered from any thread, main(UI) or background; but AsyncTask is only triggered from the main thread

2) What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?

An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes.

Then, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created but that is not displayed anymore!). This can lead to an Exception (of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity).

There’s also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activity, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.

For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-running background tasks, a different mechanism (such as a service) should be employed.

Note: AsyncTasks by default run on a single thread using a serial executor, meaning it has only 1 thread and each task runs one after the other

How to handle crashing of AsyncTask during screen rotation?
A) The best way to handle AsyncTask crash is to create a RetainFragment, i.e., a fragment without UI as shown in the gist below: https://gist.github.com/vamsitallapudi/26030c15829d7be8118e42b1fcd0fa42 We can also avoid this crash by using RxJava instead of AsyncTask as we will be subscribing and unsubscribing at onResume() and onPause() methods respectively.

3) What is Async Task and methods of Async Task?

Answer: Async task is a class that extends object class to allow short operations to run asynchronously in the background. Async task runs in a new thread.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Methods of Asynctask are :

1.onPreExecute: a step used to set up the task

2.doInBackground: a step used to perform the actual task

3.onProgressUpdate: a step used to update the current progress status of the task that is being performed in doInBackground

4.onPostExecute: once doInBackground finishes executing the task, this step delivers the result back to the main UI thread and stops the AsyncTask process

WHICH CLASSES CAN YOU USE FOR THREADING IN ANDROID?

Android provide several different classes to handle threading:

-AsyncTask : One of the first classes introduced in Android since 1.6. It encapsulates a

background process, that synchronizes with the main thread.

-Handler : a Handler object can send Messages and Runnable objects. Each Handler is

always associated with a different Thread .

-Threads: this is the default Java class for Threads. It extends from

java.util.concurrent. It is somehow a little bit antiquate, and there is some functionality

lacking for modern software environments (i.e., no default pooling or handling

configuration changes)

What are some of the cases that you would need to handle when using AsyncTask?

Screen rotation : Suppose the device is rotated then the Activity will be recreated making the reference to the Activity invalid. This would even cause memory leaks as the AsyncTask might have a reference to the Activity or worse Views or the AsyncTask is implemented as a nested class of the Activity.
Activity is destroyed: This is very similar to the first one, AsyncTask continues to execute even if the Activity is destroyed.
Need to explicitly implement the cancel logic : If AsyncTask.cancel() is called then AsyncTask.isCancelled() returns true and developer is supposed to handle the AsyncTask.isCancelled() being true case.
By default AsyncTasks has just one worker thread

Android AsyncTask create new thread in background?

What are the advantages of AsyncTaskLoader over AsyncTask?

  • AsyncTaskLoader can an handle Activity configuration changes more easily
  • Closer relationship with Activity/Fragment life-cycle

A) True

In Android, it is very normal to found memory leak scenario as many tasks are running in the background thread. Many time if Activity or fragment who start background thread using Async task is killed, Still the background thread will be alive.

We can handle this problem by calling the method removeCallbacksAndMessages on the handler in the onDestroy method of the activity.

If we cancel the task, we will not cause a memory leak. We can also solve that problem by constructing the new Java file with a context.getApplicationContext() instead of normal getContext / this (Activity). Then it will not be tied to the activity but to the application. We won't be able to access the dialog in onPostExecute(). Instead, we can use a callback to a listener if we want. 

Please find below code for more detail:

 @Override
    protected void onDestroy() {
        super.onDestroy();
        //This resolves the memory leak by removing the handler references.
        mHandler.removeCallbacksAndMessages(null);

Handler: 

What are Handlers?

Handlers are objects for managing threads. It receives messages and writes code on how to handle the message. They run outside of the activity’s lifecycle, so they need to be cleaned up properly or else you will have thread leaks.

  • Handlers allow communicating between the background thread and the main thread.
  • A Handler class is preferred when we need to perform a background task repeatedly after every x seconds/minutes.

What is a Handler typically used for?

Typically it is used to perform an action on a different thread than your own.

It is also used to schedule messages and runnables to be executed at some point in the future.

Background: In the most cases, you’ll use a Handler in a background thread to perform some kind of action in the main thread. The Handler objects registers itself in the thread in which it is created and provides a communication channel to this thread.

Example:

public class MyActivity extends Activity {
	private ProgressBar progress;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.example);
		progress = (ProgressBar) findViewById(R.id.myProgressBar);
	}

	public void startSuperLongProcessing(View view) {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				progress.post(new Runnable() { // uses the Handler from the View element
					@Override
					public void run() {
						progress.setProgress(100); // executes this statement on the Main thread
					}
				});
			}
		};
		new Thread(runnable).start(); // starts the thread
	}
}

WOULD YOU UPDATE AFTER AN INTERVAL AN ITEM IN YOUR SCREEN
WITH A TIMERTASK OR A HANDLER? WHY?
With a Handler , which is the way to do it in Android. Using a TimerTask introduces a
new Thread for a relatively small reason.
Aaaaass

ThreadPool:

What is a Handler typically used for?

Handler is used for two main reasons:

  • to schedule messages and runnables to be executed at some point in the future
  • to enqueue an action to be performed on a different thread than your own

1) What is a ThreadPool? And is it more effective than using several separate Threads?

Creating and destroying threads has a high CPU usage, so when we need to perform lots of small, simple tasks concurrently, the overhead of creating our own threads can take up a significant portion of the CPU cycles and severely affect the final response time. ThreadPool consists of a task queue and a group of worker threads, which allows it to run multiple parallel instances of a task



Aaaaaaassss

  • When to use AsyncTask and when to use services?
    A) Services are useful when you want to run code even when your application's Activity isn't open. AsyncTask is a helper class used to run some code in a separate thread and publish results in main thread. Usually AsyncTask is used for small operations and services are used for long running operations.

  • What is a Looper?
    A) A Looper is a class used to loop through the Message Queue attached to the Thread. By default, a thread halts when the execution completes. But, for Example, if we take Android's Main thread, it should not halt upon execution. Rather it should loop through the runnables(Messages) that its assigned in order to work properly. For more info, refer to this link.

  • What is a Handler?

  • A) A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.


9. What are the steps to implement Loader?

SHOW/HIDE ANSWER
  • Initialize the LoadManager or restart it with initLoader or restartLoader respectively
  • Implement the Loader implementation class
  • Override the LoaderManager.LoaderCallbacks
  • Return your Loader implementation from onCreateLoader
  • Use the data from onLoadFinished
Reference
http://developer.android.com/guide/components/loaders.html

Comments

Popular posts from this blog

Jetpack Compose based Android interview and questions

Null safety based Kotlin interview questions and answers

What are Support Libraries ?