Question 1. What Is Thread In Java?
Threads consumes CPU in satisfactory possible manner, subsequently allows multi processing. Multi threading reduces idle time of CPU which improves performance of application.
Thread are light weight system.
A thread elegance belongs to java.Lang package deal.
We can create a couple of threads in java, despite the fact that we don’t create any Thread, one Thread at least do exist i.E. Primary thread.
Multiple threads run parallely in java.
Threads have their own stack.
Advantage of Thread : Suppose one thread desires 10 mins to get positive task, 10 threads used at a time ought to entire that venture in 1 minute, due to the fact threads can run parallely.
Question 2. What Is Difference Between Process And Thread In Java?
One manner can have multiple Threads,Thread are subdivision of Process. One or extra Threads runs in the context of method. Threads can execute any part of procedure. And same part of technique can be carried out by way of a couple of Threads.
Processes have their own copy of the information section of the discern technique while Threads have direct get entry to to the statistics segment of its method.Processes have their own address even as Threads proportion the deal with space of the technique that created it.
Process introduction needs whole lot of stuff to be achieved, we'd want to replicate complete figure technique, but Thread can be easily created.Processes can without difficulty communicate with baby processes but interprocess communication is tough. While, Threads can easily communicate with different threads of the identical manner the usage of wait() and notify() strategies.
In system all threads percentage system aid like heap Memory and so on. Even as Thread has its personal stack.Any trade made to method does now not affect child procedures, however any exchange made to string can affect the behavior of the opposite threads of the process.Example to peer in which threads on are created on different processes and same method.
Adv Java Interview Questions
Question three. How To Implement Threads In Java?
Threads can be created in two methods i.E. Via enforcing java.Lang.Runnable interface or extending java.Lang.Thread class after which extending run technique.
Thread has its very own variables and strategies, it lives and dies at the heap. But a thread of execution is an person process that has its personal call stack. Thread are light-weight system in java.
1.Thread introduction via implementingjava.Lang.Runnableinterface.
We will create object of class which implements Runnable interface :
MyRunnable runnable=new MyRunnable();
Thread thread=new Thread(runnable);
2.And then create Thread object by means of calling constructor and passing reference of Runnable interface i.E. Runnable item :
Thread thread=new Thread(runnable);
Question four. We Should Implement Runnable Interface Or Extend Thread Class. What Are Differences Between Implementing Runnable And Extending Thread?
Thread simplest while you are seeking to alter run() and other techniques as well. If you are simply trying to adjust only the run() technique imposing Runnable is the first-class alternative (Runnable interface has simplest one abstract approach i.E. Run() ).
Differences between implementing Runnable interface and extending Thread elegance -
1. Multiple inheritance in now not allowed in java : When we implement Runnable interface we are able to make bigger another magnificence as nicely, but if we increase Thread elegance we can't make bigger some other magnificence due to the fact java does no longer allow a couple of inheritance. So, same paintings is done by imposing Runnable and lengthening Thread but in case of implementing Runnable we are nonetheless left with alternative of extending a few different magnificence. So, it’s better to put into effect Runnable.
2. Thread protection : When we put into effect Runnable interface, equal object is shared among a couple of threads, but whilst we amplify Thread class every and each thread gets related to new object.
3. Inheritance (Implementing Runnable is light-weight operation) : When we enlarge Thread unnecessary all Thread magnificence features are inherited, but while we enforce Runnable interface no greater function are inherited, as Runnable simplest is composed best of 1 summary method i.E. Run() method. So, implementing Runnable is light-weight operation.
4. Coding to interface : Even java recommends coding to interface. So, we should put in force Runnable as opposed to extending thread. Also, Thread magnificence implements Runnable interface.
5. Don’t enlarge unless you wanna modify fundamental behaviour of sophistication, Runnable interface has best one summary approach i.E. Run() : We have to enlarge Thread simplest when you are seeking to alter run() and different techniques as well. If you're definitely seeking to regulate most effective the run() technique enforcing Runnable is the excellent choice (Runnable interface has simplest one abstract technique i.E. Run() ). We have to now not enlarge Thread magnificence unless we are seeking to modify essential behaviour of Thread elegance.
6. Flexibility in code when we put in force Runnable : When we enlarge Thread first a fall all thread capabilities are inherited and our class becomes direct subclass of Thread , so anything action we're doing is in Thread elegance. But, when we put into effect Runnable we create a new thread and bypass runnable object as parameter,we could skip runnable item to executorService & a whole lot greater. So, we've got extra alternatives when we implement Runnable and our code will become extra flexible.
7. ExecutorService : If we put in force Runnable, we are able to begin a couple of thread created on runnable item with ExecutorService (due to the fact we are able to begin Runnable object with new threads), however not inside the case when we enlarge Thread (because thread may be started out only as soon as).
Adv Java Tutorial
Question five. We Should Implement Runnable Interface Or Extend Thread Class. What Are Differences Between . How Can You Say Thread Behaviour Is Unpredictable?
Thread behaviour is unpredictable because execution of Threads depends on Thread scheduler, thread scheduler might also have unique implementation on extraordinary platforms like windows, unix and so forth. Same threading application may also produce specific output in subsequent executions even on same platform.
To obtain we're going to create 2 threads on equal Runnable Object, create for loop in run() approach and start both threads. There is not any surety that which threads will whole first, each threads will enter anonymously in for loop.
J2EE Interview Questions
Question 6. When Threads Are Not Lightweight Process In Java?
Threads are light-weight technique best if threads of same system are executing simultaneously. But if threads of different tactics are executing concurrently then threads are heavy weight procedure.
Question 7. How Can You Ensure All Threads That Started From Main Must End In Order In Which They Started And Also Main Should End In Last?
We can use join() methodto make sure all threads that began from important must end in order wherein they commenced and also principal need to result in remaining.In different phrases waits for this thread to die. Calling be a part of() method internally calls be part of(zero);
DETAILED DESCRIPTION : Join() method - make sure all threads that started from predominant ought to end in order in which they started and additionally major need to end in final. Types of join() technique with packages- 10 salient functions of be part of.
J2EE Tutorial Core Java Interview Questions
Question eight. What Is Difference Between Starting Thread With Run() And Start() Method?
When you call begin() method, most important thread internally calls run() approach to begin newly created Thread, so run() technique is in the end referred to as through newly created thread.
When you name run() approach essential thread rather than starting run() method with newly thread it start run() approach by way of itself.
Question 9. What Is Significance Of Using Volatile Keyword?
Java lets in threads to get right of entry to shared variables. As a rule, to make certain that shared variables are consistently up to date, a thread must ensure that it has different use of such variables by means of obtaining a lock that enforces mutual exclusion for those shared variables.
If a area is asserted risky, in that case the Java memory model ensures that all threads see a steady cost for the variable.
Few small questions>
Q. Can we have volatile methods in java?
1. No, risky is simplest a keyword, can be used best with variables.
Q. Can we've got synchronized variable in java?
1. No, synchronized can be used handiest with techniques, i.E. In technique declaration.
JSP Interview Questions
Question 10. What Are Thread Priorities?
Thread Priority range is from 1 to 10.
Where 1 is minimum priority and 10 is most priority.
Thread elegance offers variables of final static int type for placing thread precedence.
/* The minimal priority that a thread can have. */
/* The default priority this is assigned to a thread. */
/* The most precedence that a thread could have. */
Thread with MAX_PRIORITY is in all likelihood to get extra CPU as compared to low priority threads. But sometimes low precedence thread may get extra CPU. Because thread scheduler schedules thread on discretion of implementation and thread behaviour is totally unpredictable.
Thread with MIN_PRIORITY is likely to get much less CPU as compared to excessive priority threads. But every now and then excessive priority thread might much less CPU. Because thread scheduler schedules thread on discretion of implementation and thread behaviour is totally unpredictable.
SetPriority()method is used for Changing the priority of thread.
GetPriority()method returns the thread’s priority.
Core Java Tutorial
Question eleven. What Is Threadgroup In Java, What Is Default Priority Of Newly Created Threadgroup, Mention Some Important Threadgroup Methods?
When program begins JVM creates a ThreadGroup named important. Unless designated, all newly created threads turn out to be individuals of the primary thread institution.
ThreadGroup is initialized with default precedence of 10.
ThreadGroup crucial techniques >
o call of ThreadGroup.
ocount of active companies in ThreadGroup.
ocount of lively threads in ThreadGroup.
olist() technique has prints ThreadGroups information
oMethod returns the maximum precedence of ThreadGroup.
oSets the most priority of ThreadGroup.
Java-Springs Interview Questions
Question 12. What Is Addshutdownhook Method In Java?
addShutdownHook approach in java >
•addShutdownHook technique registers a brand new digital-gadget shutdown hook.
•A shutdown hook is a initialized however unstarted thread.
•When JVM begins its shutdown it will begin all registered shutdown hooks in a few unspecified order and let them run concurrently.
When JVM (Java digital gadget) shuts down >
•When the last non-daemon thread finishes, or
•while the System.Go out is known as.
Once JVM’s shutdown has begunnew shutdown hook cannot be registered neither formerly-registered hook can be de-registered. Any strive made to do any of those operations causes an IllegalStateException.
For greater element with software examine : Threads addShutdownHook approach in java
Adv Java Interview Questions
Question 13. What Do You Mean By Thread Starvation?
When thread does now not sufficient CPU for its execution Thread starvation takes place.
Thread starvation may additionally manifest in following eventualities >
•Low priority threads receives less CPU (time for execution) compared to excessive priority threads. Lower precedence thread might also starve away waiting to get sufficient CPU to carry out calculations.
•In deadlock threads waits for each other to launch lock holded by them on assets. There each Threads starves away to get CPU.
•Thread might be ready indefinitely for lock on object’s reveal (by way of calling wait() method), because no different thread is asking notify()/notifAll() method on item. In that case, Thread starves away to get CPU.
•Thread is probably waiting indefinitely for lock on item’s monitor (via calling wait() approach), but notify() can be time and again awakening some other threads. In that case additionally Thread starves away to get CPU.
Question 14. Can You Find Whether Thread Holds Lock On Object Or Not?
holdsLock(item) method can be used to discover whether current thread holds the lock on display of detailed object.
HoldsLock(object) method returns true if the contemporary thread holds the lock on screen of specified item.
Question 15. Can A Constructor Be Synchronized?
No, constructor can not be synchronized. Because constructor is used for instantiating item, whilst we're in constructor item is underneath introduction. So, till item is not instantiated it does not want any synchronization.
Enclosing constructor in synchronized block will generate compilation error.
Using synchronized in constructor definition will also show compilation mistakes.
COMPILATION ERROR = Illegal modifier for the constructor in kind ConstructorSynchronizeTest; simplest public, included & private are accepted
Though we can use synchronized block inside constructor.
JMS(Java Message Service) Interview Questions
Question sixteen. What Is Significance Of Yield() Method, What State Does It Put Thread In?
yield() is a local method it’s implementation in java 6 has been changed as compared to its implementation java 5. As method is local it’s implementation is furnished via JVM.
In java five, yield() approach internally used to call sleep() method giving all of the other threads of equal or higher priority to execute earlier than yielded thread with the aid of leaving allotted CPU for time hole of 15 millisec.
But java 6, calling yield() approach offers a touch to the thread scheduler that the cutting-edge thread is inclined to yield its modern-day use of a processor. The thread scheduler is loose to ignore this hint. So, once in a while even after the usage of yield() method, you may not be aware any distinction in output.
Salient functions of yield() technique >
•Definition : yield() technique while known as on thread gives a hint to the thread scheduler that the cutting-edge thread is inclined to yield its modern use of a processor.The thread scheduler is unfastened to ignore this hint.
•Thread kingdom : while yield() method is referred to as on thread it goes from strolling to runnable state, now not in waiting country. Thread is eligible to run however no longer running and can be picked through scheduler at each time.
•Waiting time : yield() method stops thread for unpredictable time.
•Static approach : yield()is a static approach, therefore calling Thread.Yield() reasons presently executing thread to yield.
•Native approach : implementation of yield() method is furnished through JVM.
Let’s see definition of yield() method as given in java.Lang.Thread -
public static native void yield();
•synchronized block : thread want not to to acquire object lock before calling yield()method i.E. Yield() technique can be called from outside synchronized block.
Question 17. What Is Significance Of Sleep() Method In Detail, What State Does It Put Thread In?
sleep() is a native technique, it’s implementation is supplied through JVM.
10 salient functions of sleep() approach >
•Definition : sleep() techniques causes current thread to sleep for designated range of milliseconds (i.E. Time passed in sleep method as parameter). Ex- Thread.Sleep(10) causes currently executing thread to sleep for 10 millisec.
•Thread kingdom : when sleep() is referred to as on thread it is going from jogging to ready state and may return to runnable state while sleep time is up.
•Exception : sleep() method need to seize or throw compile time exception i.E. InterruptedException.
•Waiting time : sleep() method have got few options.
1.Sleep(long millis) - Causes the currently executing thread to sleep for the desired quantity of milliseconds
public static local void sleep(lengthy millis) throws InterruptedException;
1.Sleep(long millis, int nanos) - Causes the currently executing thread to sleep for the desired number of milliseconds plus the required range of nanoseconds.
Public static local void sleep(long millis,int nanos) throws InterruptedException;
•static technique : sleep()is a static method, reasons the presently executing thread to sleep for the specified wide variety of milliseconds.
•Belongs to which class :sleep() technique belongs to java.Lang.Thread magnificence.
•synchronized block : thread need now not to to collect item lock earlier than calling sleep()approach i.E. Sleep() approach can be referred to as from outside synchronized block.
Java applet Interview Questions
Question 18. Difference Between Wait() And Sleep()?
•Should be known as from synchronized block :wait() approach is usually referred to as from synchronized block i.E. Wait() approach desires to lock object reveal earlier than object on which it's far called. But sleep() approach can be known as from out of doors synchronized block i.E. Sleep() method doesn’t want any object screen.
•IllegalMonitorStateException : if wait() technique is called without obtaining item lock than IllegalMonitorStateException is thrown at runtime, however sleep() methodnever throws such exception.
•Belongs to which class : wait() technique belongs to java.Lang.Object magnificence however sleep() method belongs to java.Lang.Thread magnificence.
•Called on item or thread : wait() approach is referred to as on gadgets but sleep() approach is known as on Threads now not objects.
•Thread nation : when wait() approach is known as on item, thread that holded item’s monitor goes from walking to waiting nation and can return to runnable nation best whilst notify() or notifyAll()method is called on that item. And later thread scheduler schedules that thread to move from from runnable to walking kingdom.
While sleep() is referred to as on thread it is going from strolling to ready country and may go back to runnable kingdom while sleep time is up.
•When known as from synchronized block :when wait() technique is referred to as thread leaves the object lock. But sleep()approach when called from synchronized block or technique thread doesn’t leaves item lock.
J2EE Interview Questions
Question 19. Differences And Similarities Between Yield() And Sleep()?
Differences yield() and sleep() :
•Definition : yield() approach while referred to as on thread offers a hint to the thread scheduler that the present day thread is inclined to yield its current use of a processor.The thread scheduler is free to disregard this trace. Sleep() techniques reasons modern thread to sleep for precise number of milliseconds (i.E. Time handed in sleep method as parameter). Ex- Thread.Sleep(10) causes currently executing thread to sleep for 10 millisec.
•Thread nation : whilst sleep() is referred to as on thread it goes from strolling to ready state and might return to runnable state when sleep time is up. Whilst yield() technique is referred to as on thread it goes from jogging to runnable state, no longer in ready nation. Thread is eligible to run however now not going for walks and may be picked via scheduler at anytime.
•Exception : yield() technique want no longer to trap or throw any exception. But sleep() technique have to seize or throw collect time exception i.E. InterruptedException.
•Waiting time : yield() method stops thread for unpredictable time, that relies upon on thread scheduler. But sleep() method have were given few options.
1.Sleep(long millis) - Causes the currently executing thread to sleep for the specified quantity of milliseconds
2.Sleep(lengthy millis, int nanos) - Causes the presently executing thread to sleep for the specified quantity of milliseconds plus the desired range of nanoseconds.
Similarity among yield() and sleep():
> yield() and sleep() technique belongs to java.Lang.Thread elegance.
> yield() and sleep() method may be called from out of doors synchronized block.
> yield() and sleep() approach are called on Threads not items.
Question 20. Can You Again Start Thread?
No, we can not begin Thread once more, doing so will throw runtimeException java.Lang.IllegalThreadStateException. The motive is as soon as run() technique is completed by Thread, it is going into dead state.
Let’s take an example-
Thinking of beginning thread again and calling begin() technique on it (which internally is going to name run() technique) for us is some what like asking useless man to awaken and run. As, after finishing his existence man or woman goes to useless nation.
Java Interview Questions
Question 21. How Threads Communicate Between Each Other?
Threads can talk with every different by means of using wait(), notify() and notifyAll() methods.
Question 22. Why Wait(), Notify() And Notifyall() Are In Object Class And Not In Thread Class?
1.Every Object has a monitor, obtaining that monitors allow thread to hold lock on object. But Thread elegance does no longer have any video display units.
1.Wait(), notify() and notifyAll()are referred to as on objects only >When wait() technique is called on object by using thread it waits for some other thread on that item to release item display with the aid of calling notify() or notifyAll() method on that object.
When notify() approach is called on object through thread it notifies all the threads
which might be looking ahead to that item reveal that item screen is to be had now.
So, this shows that wait(), notify() and notifyAll() are known as on items best.
Now, Straight forward query that involves thoughts is how thread acquires object lock by way of obtaining object display? Let’s try to understand this simple idea in detail?
1.Wait(), notify() and notifyAll() method being in Object class lets in all of the threads created on that object to communicate with different.
2.As multiple threads exists on equal item. Only one thread can keep object monitor at a time. As a end result thread can notify different threads of same object that lock is to be had now. But, thread having these methods does no longer make any sense because a couple of threads exists on object its not different way around (i.E. Multiple objects exists on thread).
3.Now allow’s talk one hypothetical scenario, what will appear if Thread magnificence carries wait(), notify() and notifyAll() methods?
Having wait(), notify() and notifyAll() methods way Thread elegance additionally have to have their display.
Every thread having their display will create few troubles -
>Thread verbal exchange trouble.
>Synchronization on object received’t be feasible- Because object has display, one item can have a couple of threads and thread preserve lock on object via holding object monitor. But if every thread may have monitor, we received’t have any manner of reaching synchronization.
>Inconsistency in country of item (due to the fact synchronization may not be feasible).
Java eight Tutorial
Question 23. Is It Important To Acquire Object Lock Before Calling Wait(), Notify() And Notifyall()?
Yes, it’s obligatory to collect object lock before calling these methods on object. Wait(), notify() and notifyAll() techniques are continually known as from Synchronized block simplest, and as quickly as thread enters synchronized block it acquires object lock (by retaining object monitor). If we name those methods with out obtaining object lock i.E. From outside synchronize block then java.Lang. IllegalMonitorStateException is thrown at runtime.
Wait() technique desires to enclosed in try-trap block, because it throws compile time exception i.E. InterruptedException.
Java eight Interview Questions
Question 24. What Does The Yield() Method Do?
The yield() approach puts currently running thread in to ready nation.
Core Java Interview Questions
Question 25. What Exception Does The Wait() Method Throw?
The java.Lang.Object elegance wait() approach throws "InterruptedException".
Question 26. What Does Notifyall() Method Do?
notifyAll() technique actions all waiting threads from the ready pool to ready country.
Java Programmer Interview Questions
Question 27. What Does Wait() Method Do?
wait() method releases CPU, releases gadgets lock, the thread enters into pool of waiting threads.
JSP Interview Questions
Question 28. Explain Different Ways Of Creating A Thread. Which One Would You Prefer And Why?
There are three ways that can be used so as for a Thread to be created:
• A elegance may additionally make bigger the Thread elegance.
• A class may additionally put in force the Runnable interface.
• An utility can use the Executor framework, which will create a thread pool.
The Runnable interface is preferred, as it does no longer require an object to inherit the Thread magnificence. In case your application design requires multiple inheritance, only interfaces allow you to. Also, the thread pool may be very green and can be carried out and used very without problems.
Question 29. Explain The Available Thread States In A High-level?
During its execution, a thread can reside in one of the following states:
• Runnable: A thread will become prepared to run, however does now not necessarily start running right away.
• Running: The processor is actively executing the thread code.
• Waiting: A thread is in a blocked nation awaiting some outside processing to finish.
• Sleeping: The thread is compelled to sleep.
• Blocked on I/O: Waiting for an I/O operation to finish.
• Blocked on Synchronization: Waiting to collect a lock.
• Dead: The thread has finished its execution.
Question 30. What Is The Difference Between A Synchronized Method And A Synchronized Block?
In Java programming, each object has a lock. A thread can accumulate the lock for an item with the aid of using the synchronized key-word.
The synchronized keyword may be implemented in a technique stage (coarse grained lock) or block degree of code (exceptional grained lock).
Question 31. How Does Thread Synchronization Occurs Inside A Monitor ? What Levels Of Synchronization Can You Apply?
The JVM makes use of locks in conjunction with video display units. A reveal is largely a guardian that watches over a series of synchronized code and making sure that only one thread at a time executes a synchronized piece of code. Each screen is associated with an object reference. The thread isn't always allowed to execute the code till it obtains the lock.
Question 32. How Do You Ensure That N Threads Can Access N Resources Without Deadlock?
A quite simple manner to avoid deadlock even as the usage of N threads is to impose an ordering on the locks and force every thread to observe that ordering. Thus, if all threads lock and unencumber the mutexes within the equal order, no deadlocks can get up.
Question 33. What Is The Difference Between Sleep() And Yield()?
When a Thread calls the sleep() approach, it's going to return to its waiting country. When a Thread calls the yield() method, it returns to the equipped nation.
Java-Springs Interview Questions
Question 34. What Is A Daemon Thread?
Daemon is a low priority thread which runs in the backgrouund.
Question 35. How To Make A Normal Thread As Daemon Thread?
We need to call setDaemon(real) technique on the thread object to make a thread as daemon thread.
Question 36. What Is The Difference Between Normal Thread And Daemon Thread?
Normal threads do mainstream activity, whereas daemon threads are used low precedence work. Hence daemon threads also are stopped while there are no normal threads.
JMS(Java Message Service) Interview Questions
Question 37. What Does The Start() Method Of Thread Do?
The thread's start() approach puts the thread in equipped country and makes the thread eligible to run. Start() approach routinely calls the run () technique.
Question 38. What Are The Two Ways That A Code Can Be Synchronised?
Method can be declared as synchronised.
A block of code be sychronised.
Question 39. Can You Declare A Static Method As Synchronized?
Yes, we will claim static approach as synchronized. But the calling thread need to accumulate lock at the magnificence that owns the technique.
Question 40. What Are All The Methods Used For Inter Thread Communication And What Is The Class In Which These Methods Are Defined?
a. Wait(),notify() & notifyall()
b. Object elegance
Java applet Interview Questions