September 5, 2017

Java Threading Interview Questions Answers


What is a thread? What are the advantages we derived by programming with thread?

Threads allow programs to execute simultaneously. A thread is an independent path of execution in a program. These threads can be executed synchronously or asynchronously. All threads have a priority attached. Thread with a higher priority is executed first.

Advantages:

- Allows multiple programs to be executed concurrently
- Cost of thread is low compared to processes in terms of space and communication.
- Threads are lightweight.

Explain how to create a thread and start it running.

There are 2 ways in which a thread can be created.

By extending the Thread class wherein the subclass needs to override the run method. Then just an instance of that class needs to be created and [classname].start() would start it running.

The other way is to declare a class that implements the runnable interface. Then the run() method needs to be implemented.
Then with following code the thread can be created and run.
SubThread a = new SubThread (143);
new Thread(a).start();

How does thread’s stop method work?

Stop() method of thread stops the thread execution.

The security manager, if present, checks if the current thread is trying to stop some other thread. The stop method to stop the thread is an unsafe option. Stopping a thread causes it to unlock all the monitors it has locked. It causes the damaged objects to be read by some other threads. These objects are damaged because they are left in an inconsistent state on stopping the thread.

It is always better to write a code which will modify some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running.

How do we specify pause times in my program?

- Using the sleep function in Java, the thread’s execution can be put on hold. During this pause session, the thread does not loose ownership of the monitors.

- Syntax:

Public static void sleep(long millis)
Throws InterruptedExecution

- Here, millis is the time in mili seconds to hold the threads execution.

What is multi threaded program? What is the importance of thread synchronization?

A multi threaded program involves multiple threads of control in a single program. Each thread has its own stack. Other resources of the process are shared by all threads and while trying to access them it should be synchronized.

Importance of thread synchronization

- Avoids issues like deadlocks and starvation
- Can be used for debugging multi threaded programs

When a thread is created and started, what is its initial state?

A thread is in “Ready” state after it has been created and started.
This state signifies that the thread is ready for execution. From here, it can be in the running state.

What are the high-level thread states?

The thread can be in one of the following states:

- Running state: A thread which is in running state has an access to the CPU. This means that the thread is being executed.

- Ready state: A thread is in “Ready” state after it has been created and started. This state signifies that the thread is ready for execution. From here, it can be in the running state

- Dead state: The thread reaches the Death state when it has finished execution. From here on it cannot be executed.

- Waiting state: in this state, the thread is waiting for some action to happen. Once the action happens, the thread is in ready state.

- This waiting thread can be in either sleep, suspend, block or waiting for monitor state.

What is the difference between preemptive scheduling and time slicing?

- Preemptive scheduling enables the highest priority task execution until waiting or dead states entered. It also executes, until a higher priority task enters.

- Time slicing allows a task to execute for a stipulated time slice and then reenters the pool of ready tasks. At that time the scheduler determines the executable task, based on the priority and various other tasks.

- If a certain task is running and the scheduling method used is preemptive, and then if there is another task that has a higher priority than the executing task, the executing task is preempted by the higher priority task.

- In time slicing methods, a task executes for a predefined slice of time. After the execution of that task, if there is another task with a higher priority, the scheduler executes the priority task the next depending on priority and other factors.

What is a task's priority and how is it used in scheduling?

Every task is assigned a priority for execution. The task with the highest priority is executed first. The low priority task is executed after that. This task priority is a simple integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

What is a monitor?

- It can be considered as a building which contains a special room.

- The mechanism that Java uses to support synchronization is the monitor.

It supports two kind of thread synchronization.

1. Mutual exclusion

2. Cooperation

1. Mutual exclusion:

- Supported in JVM via object block.
- It enables multiple threads to independently work on shared data without interfering with each other.

2. Cooperation:

- Supported in JVM via wait() and notify() methods of class objects.
- It enables threads to work together towards a common goal.

Explain the use of synchronization keyword.

- It is an essential tool in concurrent programming in Java.

- A method, declared as synchronized, first attains a lock over an object before beginning an execution. Once it has finished with the execution, whether normally or abruptly, it releases the lock achieved. In this way, a method behaves as if its body were contained in a synchronized statement.

- The main purpose of synchronization keyword is to allow one thread at a time into a particular section of code. It makes the compiler append instructions to acquire the lock on the specified object before executing the code and release it afterwards.

Explain how do we allow one thread to wait while other to finish.

- The wait() method, notify() method, and notifyAll() method provide an efficient transfer of control from one thread to another.

- A thread can suspend itself using wait() method till a time another thread notifies.

- Thread groups are used to invoke methods which apply to all threads in the group.

- Using the join() method, one can allow one thread to wait while other to finish.

Syntax:

Public final void join()

- An interrupted exception is thrown if another thread has interrupted current thread.

Explain the purpose of yield() method.

- The yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute.
- This method causes on the currently executing thread object to temporarily pause and allow other threads to execute.

Declaration of yield() method:

public static void yield()

What is the difference between yielding and sleeping?

- The sleep() causes the thread to suspend its running only for a specified amount of time.
- The yield() causes the thread to join the ready queue in the CPU again.
When a thread is created and started, what is its initial state?

After a thread has been started, it could be in runnable, blocked, waiting, timed waiting or even terminated state.

What are the high-level thread states?

The high-level thread states are ready, running, waiting, and dead.



Subscribe to get more Posts :