Interview Questions.

Thread Interview Questions and Answers

fluid

Thread Interview Questions and Answers

Q1. What is a intended by using Thread?

Ans: In Java, 'thread' manner  different things:

An instance of class java.Lang.Thread.

A thread of an execution.

An instance of Thread is just an item. Like another object in Java, it has variables and techniques and lives and dies on the heap. But a thread of execution is an individual technique (a "light-weight" system) that has its personal call stack. In Java, there may be one thread in keeping with call stack or to consider it in reverse, one name stack per thread. Even in case you don't create any new threads in your application, threads returned there are running.

Q2. What is the distinction among a thread and a method?

Ans:

 

Threads share the cope with area of the technique that created it whereas procedures have their very own cope with.

Threads have direct get entry to to the statistics segment of its technique even as processes have their personal replica of the data phase of the figure technique.

Threads can without delay talk with other threads of its system while on the other hand strategies should use interprocess communique to communicate with sibling methods.

Threads have almost no overhead at the same time as approaches have great overhead.

New threads are without difficulty created while new methods require duplication of the parent procedure.

Threads can workout enormous manage over threads of the identical process while approaches can only workout manage over baby methods.

Changes to the primary thread (cancellation, precedence change, and so forth.) might also affect the behavior of the other threads of the method at the same time as changes to the parent process do no longer affect infant approaches.

Q3. What are the benefits or utilization of threads?

 

Ans:

 Threads help concurrent operations. For example:

Multiple requests by way of a consumer on a server may be handled as an person patron thread.

Threads regularly result in easier packages.

In sequential programming, updating more than one presentations normally calls for a huge while-loop that plays small components of every display update.

Threads offer a high degree of control.

 Imagine launching a complex computation that once in a while takes longer than is excellent.

Threaded programs exploit parallelism.

 A pc with more than one CPUs can literally execute more than one threads on distinctive functional devices while not having to simulate multi-tasking ("time sharing").

Q4. What are the two methods of making thread?

Ans: There are two ways to create a brand new thread. Extend the 'Thread' magnificence and override the 'run()' method to your class. Create an instance of the subclass and invoke the 'start()' approach on it, for you to create a new thread of execution.

Public elegance NewThread extends Thread

public void run()

// the code that must be carried out in a separate new thread is going here

public static void essential(String [] args)

NewThread c = new NewThread();

c.Start();

 

This will put in force the 'Runnable' interface. The class will need to put into effect the 'run()' approach in the 'Runnable' interface. Create an example of this magnificence. Pass the reference of this instance to the 'Thread' constructor and a new thread of execution will be created.

Public elegance NewThread implements Runnable

public void run()

// the code that must be done in a separate new thread is going here

public static void primary(String [] args)

NewThread c = new NewThread();

Thread t = new Thread(c);

t.Begin();

Q5. What is synchronization in appreciate to multi-threading in Java?

Ans: With admire to multi-threading, synchronization is the capability to control the access of a couple of threads to shared sources. Without synchronization, it's far viable for one Java thread to alter a shared variable even as some other thread is in the process of the usage of or updating same shared variable. This normally ends in misguided conduct or application.

Q6. Explain specific way of using thread?

Ans: A Java thread may be carried out by using using Runnable interface or via extending the Thread magnificence. The Runnable is more positive whilst you are going for a couple of inheritance.

Q7. What is the difference between Thread.Start() & Thread.Run() technique?

Ans: Thread.Begin() approach (native technique) of Thread magnificence in reality does the job of going for walks the Thread.Run() method in a thread. If we without delay call Thread.Run() method it's going to execute in equal thread, so does not remedy the purpose of making a brand new thread.

Q8. Why do we need run() & begin() technique each. Can we gain it with simplest run method?

Ans: We need run() & start() approach each due to the fact JVM needs to create a separate thread which cannot be differentiated from a ordinary technique call. So this activity is carried out by using start method local implementation which needs to be explicitly called. Another benefit of having these  techniques is we will have any item run as a thread if it implements Runnable interface. This is to avoid Java’s a couple of inheritance problems on the way to make it difficult to inherit every other class with Thread.

Q9. What is ThreadLocal elegance? How can it be used?

Ans: Below are some key factors about ThreadLocal variables

A thread-nearby variable efficaciously offers a separate reproduction of its value for each thread that uses it.

ThreadLocal times are normally non-public static fields in training that want to associate state with a thread

In the case when more than one threads get admission to a ThreadLocal example, a separate reproduction of the Threadlocal variable is maintained for each thread.

Common use is visible in DAO pattern where the DAO class can be a singleton however the Database connection may be maintained one by one for every thread. (Per Thread Singleton)

ThreadLocal variable are tough to apprehend and I propose you to apply best java ebook on concurrency: Java Concurrency in Practice

Q10. When InvalidMonitorStateException is thrown? Why?

Ans: This exception is thrown while you strive to call wait()/notify()/notifyAll() any of those strategies for an Object from a point on your software in which u are NOT having a lock on that item.(i.E. U r now not executing any synchronized block/approach of that object and nevertheless trying to name wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. On the grounds that This exception is a subclass of RuntimeException so we r no longer bound to trap it (although u may additionally if u need to). And being a RuntimeException this exception isn't mentioned inside the signature of wait(), notify(), notifyAll() techniques.

Q11. What is the distinction among sleep(), droop() and wait() ?

Ans: Thread.Sleep() takes the present day thread to a "Not Runnable" country for exact quantity of time. The thread holds the monitors it has received. For example, if a thread is walking a synchronized block or technique and sleep approach is known as then no different thread may be able to enter this block or approach. The snoozing thread can awaken when some other thread calls t.Interrupt on it. Note that sleep is a static method, that means it continually influences the modern thread (the only executing sleep method).

A common mistake is trying to call t2.Sleep() where t2 is a unique thread; even then, it is the modern-day thread with a view to sleep, not the t2 thread. Thread.Droop() is deprecated approach. Its possible to send different threads into suspended country by making a suspend approach call. In suspended state, a thread maintains all its video display units and cannot be interrupted. This might also reason deadlocks, therefore, it has been deprecated. Object.Wait() call also takes the present day thread into a "Not Runnable" kingdom, just like sleep(), however with a slight trade. Wait technique is invoked on a lock item, no longer thread.

Here is the sequence of operations you can suppose

A thread T1 is already going for walks a synchronized block with a lock on object - let's say "lockObject"

Another thread T2 comes to execute the synchronized block and find that it's already acquired.

Now T2 calls lockObject.Wait() technique for ready at the lock to be release by way of the T1 thread.

T1 thread finishes all its synchronized block work.

The T1 thread calls lockObject.NotifyAll() to notify all waiting threads that it carried out the usage of the lock.

Since the T2 thread is first inside the queue of ready it acquires the lock and begins processing.

Q12. Can two threads call two exclusive synchronized instance methods of an Object?

Ans: No. If an object has synchronized example methods then the Object itself is used a lock item for controlling the synchronization. Therefore all other instance methods need to wait until preceding approach name is finished. See the underneath sample code which demonstrates it very absolutely. The Class Common has 2 methods referred to as synchronizedMethod1() and synchronizedMethod2() MyThread elegance is calling both the techniques

public magnificence Common public synchronized void synchronizedMethod1() System.Out.Println("synchronizedMethod1 called");try Thread.Sleep(1000); seize (InterruptedException e) e.PrintStackTrace();System.Out.Println("synchronizedMethod1 done"); public synchronized void synchronizedMethod2() System.Out.Println("synchronizedMethod2 referred to as");try Thread.Sleep(one thousand); catch (InterruptedException e) e.PrintStackTrace();System.Out.Println("synchronizedMethod2 performed");public magnificence MyThread extends Thread non-public int identity = 0;private Common not unusual; public MyThread(String call, int no, Common item) superb(name);common = item;identity = no; public void run() System.Out.Println("Running Thread" + this.GetName());strive if (identification == 0) common.SynchronizedMethod1(); else common.SynchronizedMethod2(); catch (Exception e) e.PrintStackTrace(); public static void major(String[] args) Common c = new Common();MyThread t1 = new MyThread("MyThread-1", 0, c);MyThread t2 = new MyThread("MyThread-2", 1, c);t1.Start();t2.Start();

Q13. How to put into effect Threads in java?

Ans: This is very fundamental threading question. Threads may be created in two approaches i.E. With the aid of enforcing java.Lang.Runnable interface or extending java.Lang.Thread elegance after which extending run method.

Thread has its own variables and methods, it lives and dies on the heap. But a thread of execution is an individual manner that has its personal name stack. Thread are light-weight method in java.

Thread introduction by way of  implementingjava.Lang.Runnableinterface.

We will create object of class which implements Runnable interface :

MyRunnable runnable=new MyRunnable(); Thread thread=new Thread(runnable);

Q14. When threads aren't light-weight process in java?

Ans: Threads are light-weight method simplest if threads of same process are executing simultaneously. But if threads of different tactics are executing concurrently then threads are heavy weight method.

Q15. How can you make certain all threads that started out from fundamental should end in order in which they started and also essential should result in remaining? (Important)

Ans: Interviewers generally tend to recognise interviewees understanding approximately Thread strategies. So that is time to show your factor by answering correctly. We can use be part of() methodto make sure all threads that started from most important should result in order wherein they started out and additionally principal should end in closing.In other phrases waits for this thread to die. Calling join() method internally calls join(zero);

Q16. What is race condition in multithreading and how can we solve it? (Important)

Ans: This is very crucial question, this forms the middle of multi threading, you should be able to explain about race circumstance in detail. When multiple thread try to get entry to identical resource without synchronization causes race circumstance.

So we will clear up race condition by the use of either synchronized block or synchronized method. When no  threads can get right of entry to equal resource at a time phenomenon is also called as mutual exclusion.

Q17. Why wait(), notify()  and notifyAll() are in Object magnificence and not in Thread elegance? (Important)

Ans:

Every Object has a monitor, obtaining that monitors permit thread to preserve lock on object. But Thread elegance does no longer have any monitors.

Wait(), notify() and notifyAll()are known as on gadgets handiest >When wait() technique is called on object by means of thread it waits for some other thread on that object to launch object reveal by way of calling notify() or notifyAll()technique on that object.

When notify() approach is known as on object by using thread it notifies all the threads

that are watching for that object display that object screen is available now.

So, this indicates that wait(), notify() and notifyAll() are known as on objects best.

Wait(), notify() and notifyAll() approach being in Object magnificence lets in all of the threads created on that object to communicate with different.  .

As a couple of threads exists on identical object. Only one thread can maintain object reveal at a time. As a result thread can notify other threads of equal object that lock is available now. But, thread having those methods does now not make any feel due to the fact more than one threads exists on object its no longer other manner around (i.E. Multiple objects exists on thread).

Now let’s speak one hypothetical scenario, what's going to manifest if Thread magnificence incorporates wait(), notify() and notifyAll() methods?

Having wait(), notify() and notifyAll() techniques way Thread class also must have their monitor.

Every thread having their screen will create few issues -

>Thread communique hassle.

>Synchronization on item won’t be viable- Because item has reveal, one item may have a couple of threads and thread keep lock on item by retaining object reveal. But if every thread may have reveal, we gained’t have any way of accomplishing synchronization.

>Inconsistency in nation of item (due to the fact synchronization won't be viable).

Q18. Is it crucial to collect item lock earlier than calling wait(), notify() and notifyAll()?

Ans: Yes, it’s obligatory to accumulate object lock before calling these methods on object. As discussed above wait(), notify()  and notifyAll() strategies are always known as from Synchronized block simplest, and as quickly as thread enters synchronized block it acquires object lock (by using retaining object screen). If we name these techniques without obtaining item lock i.E. From outdoor synchronize block then java.Lang. IllegalMonitorStateException is thrown at runtime.

Wait() technique desires to enclosed in try-capture block, because it throws assemble time exception i.E. InterruptedException.

Q19. What is thread-safety? Is Vector a thread-secure elegance?

Ans: Thread-safety is a belongings of an object or code which guarantees that if accomplished or utilized by more than one threads in any way e.G. Examine vs write it will behave as anticipated. For example, a thread-secure counter item will no longer leave out any count if equal instance of that counter is shared amongst a couple of threads. Apparently, you could also divide series instructions in two category, thread-secure and non-thread-safe. Vector is certainly a thread-safe class and it achieves thread-protection with the aid of synchronizing methods which alter kingdom of Vector, however, its counterpart ArrayList isn't thread-secure.

Q20. What occurs when an Exception happens in a thread? (answer)

Ans: This is one of the proper tricky Java question I even have seen in interviews. In easy phrases, If now not caught thread will die, if an uncaught exception handler is registered then it'll get a name lower back. Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will question the thread for its UncaughtExceptionHandler the use of Thread.GetUncaughtExceptionHandler() and could invoke the handler's uncaughtException() method, passing the thread and the exception as arguments.

Q21. How do you percentage data among  thread in Java? (solution)

Ans: You can percentage information between threads by means of using shared item, or concurrent statistics shape like BlockingQueue. See this academic to learn  inter-thread communique in Java. It implements Producer patron sample the usage of wait and notify methods, which involves sharing items between two threads.




CFG