Question 1. What Is Thread In Java?
A thread is a lightweight sub technique. It is an independent direction of execution. A thread is accomplished interior a manner and one method can have more than one threads. All the threads inside a process shares a not unusual reminiscence region. Since threads are unbiased, if an exception occurs in a single thread, it doesn’t affect different threads. Threads are used to take gain of more than one CPU cores to be had in a device.
Question 2. What Is The Difference Between Thread And Process In Java?
A system is a application in execution. It also can be defined as a self contained execution surroundings.
A Thread is a single undertaking of execution in the technique. One procedure will have a couple of threads.
A manner has its personal reminiscence area.
A thread makes use of the system’s reminiscence area and percentage it with the opposite threads inside the method.
Adv Java Interview Questions
Question 3. Can We Call Run() Method Of A Thread Class?
Yes, we will call run() approach of a Thread elegance however it's going to behave like a ordinary technique and a new thread will not be created to execute the run() method. In this example the run() method can be accomplished inside the same thread which called the run technique. To truely execute it in a brand new Thread, we want to begin it the usage of Thread.Start() approach.
Question four. How Does Thread Communicate With Each Other?
Threads can communicate the usage of wait(), notify() and notifyAll() methods. Read this put up to recognize inter thread communique.
Adv Java Tutorial
Question five. Explain About Thread Priority?
Every thread has a priority, generally higher precedence thread receives priority in execution however it relies upon on Thread Scheduler implementation that is OS established. We can specify the priority of thread the use of Thread’s setPriority(int) approach but it doesn’t assure that higher priority thread gets completed earlier than lower priority thread. Thread precedence is an int whose price varies from 1 to ten wherein 1 is the bottom priority and 10 is the highest priority.
J2EE Interview Questions
Question 6. What Is A Daemon Thread?
Daemon threads are non-person threads. They are commonly used to perform low-precedence tasks that need to not take precedence over the principle challenge of the program. They can be used to do useful work whilst all different user threads are blocked. The rubbish collector is one example of a daemon thread.
JVM terminates itself while all non-daemon threads (person threads) finishes their execution, JVM does not care despite the fact that a few Daemon threads are going for walks. If JVM unearths walking daemon thread (upon finishing touch of person threads), it terminates the thread and after that shutdowns itself. You can make a consumer thread to Daemon by means of the use of setDaemon() technique of thread class.
A infant thread made out of daemon thread is also a daemon thread.
Question 7. What Is Difference Between User Thread And Daemon Thread?
By default a thread created in a Java program is always a person thread but we can make it daemon by way of calling setDaemon(true) approach, if needed. A daemon thread runs within the heritage and doesn’t prevent JVM from terminating. As quickly as all consumer thread finishes execution, Java application or JVM terminates itself, JVM doesn’t anticipate daemon thread to complete their execution. As quickly as ultimate non daemon thread finished, JVM terminates regardless of how many Daemon thread exists or jogging interior JVM.
J2EE Tutorial Core Java Interview Questions
Question 8. What Is Volatile In Java?
unstable is a special modifier that is used to indicate that a variable’s price could be modified by means of one of a kind threads. The risky key-word will mark a Java variable as “being stored in principal memory”. The value of this variable will never be cached locally: all reads and writes will pass immediately to “main memory”. Volatile variable guarantees that a write will happen before any next examine. Access to the variable acts as although it is enclosed in a synchronized block.
Question nine. What Does Yield Method Of Thread Class Do?
yield() method causes the presently executing thread object to briefly pause and allow different threads to execute. If there may be no ready thread or all of the waiting threads have a decrease precedence than the present day thread, then the equal thread will maintain its execution. When the yielded thread gets the threat for execution is decided with the aid of the thread scheduler whose behavior is platform established.
JSP Interview Questions
Question 10. What Does The Join() Method In Thread Class Do?
The be a part of method lets in one thread to look ahead to the of entirety of some other. If t is a Thread item whose thread is presently executing, t.Join() causes the modern thread(the thread which calls t.Be a part of(), mostly the principle thread) to pause execution till t’s thread terminates.
Core Java Tutorial
Question eleven. What Is The Difference Between Notify() And Notifyall()?
notify() approach wakes up a unmarried thread this is ready on this object’s screen. If any threads are waiting in this item, one in every of them is chosen to be wakened. The choice is random and happens at the discretion of the implementation. NotifyAll() wakes up all threads which are ready on this item’s screen. A thread waits on an item’s display via calling one of the wait methods.
Java-Springs Interview Questions
Question 12. How Can You Ensure All Threads That Started From Main Must End In Order In Which They Started?
We can use join() technique to make sure all threads that began from important will lead to order in which they started and also most important should lead to closing.
Adv Java Interview Questions
Question 13. Why Thread Communication Methods Wait(), Notify() And Notifyall() Are In Object Class?
In Java, wait and notify methods acts as synchronization utility and are critical methods for inter thread communication. Hence these methods are defined in Object magnificence so that every item could have get entry to to it. Also each Object has a display and Locks are made available on consistent with Object foundation. This is every other purpose why wait and notify is said in Object class as an alternative then Thread magnificence.
Question 14. Can A Constructor Be Synchronized?
No, constructor cannot be synchronized. Constructor is used for instantiating object and whilst we are in constructor, object is under introduction. So, till object isn't always instantiated it does now not want any synchronization.
Question 15. How Can You Access The Current Thread In Java?
The contemporary thread may be accessed through calling the static approach currentThread() of the java.Lang.Thread elegance. E.G. Thread.CurrentThread().GetName().
JMS(Java Message Service) Interview Questions
Question 16. What Happens When An Uncaught Exception Occurs In The Run() Method?
When an unchecked exception has happened in the run() method, the thread is stopped by means of the Java Virtual Machine. It is viable to catch this exception by way of registering an example that implements the interface UncaughtExceptionHandler as an exception handler.
The handler may be registered via invoking the static method Thread.SetDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) or through invoking setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) at the thread instance which tells the JVM to apply the furnished handler in case there was no precise handler registered at the thread.
Question 17. What Do You Mean By An Atomic Operation?
In programming, an atomic operation is one that effectively takes place . An atomic operation cannot forestall in the center: it either occurs absolutely, or it doesn’t manifest at all. No side consequences of an atomic operation are seen until the motion is complete.
Reads and writes are atomic for reference variables and for maximum primitive variables (all types except lengthy and double).
Reads and writes are atomic for all variables declared volatile (which include long and double variables).
All operations of java.Concurrent.Atomic* training
Atomic movements can not be interleaved, so they can be used with out fear of thread interference. However, this doesn't get rid of all want to synchronize atomic movements, due to the fact memory consistency errors are still possible.
Java applet Interview Questions
Question 18. What Happens If A Start Method Is Not Invoked And The Run Method Is Directly Invoked?
If a thread has been instantiated however no longer started its is said to be in new state. Unless until a begin() method is invoked on the example of the thread, it's going to not said to be alive. If you do not call a begin() approach on the newly created thread example thread isn't always taken into consideration to be alive. If the start() method is not invoked and the run() approach is immediately known as at the Thread instance, the code within the run() technique will no longer run in a separate new thread however it will start strolling within the present thread.
J2EE Interview Questions
Question 19. What Happens When Start() Is Called?
A new thread of execution with a brand new call stack starts offevolved. The state of thread modifications from new to runnable. When the thread receives hazard to execute its target run() method starts offevolved to run.
Question 20. If Code Running Is A Thread Creates A New Thread What Will Be The Initial Priority Of The Newly Created Thread?
When a code walking in a thread creates a new thread item, the concern of the brand new thread is ready same to the priority of the thread which has created it.
Java Interview Questions
Question 21. What Are The Different States Of A Thread's Life Cycle?
The different states of threads are as follows:
New – When a thread is instantiated it's miles in New state till the begin() technique is known as at the thread example. In this country the thread isn't taken into consideration to be alive.
Runnable – The thread enters into this state after the start method is referred to as within the thread instance. The thread may additionally enter into the Runnable nation from Running nation. In this country the thread is considered to be alive.
Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts jogging and the thread is said to be in Running country.
Waiting/Blocked/Sleeping – In those states the thread is stated to be alive however not runnable. The thread switches to this country due to motives like wait method referred to as or sleep approach has been known as on the going for walks thread or thread might be looking ahead to some i/o aid so blocked.
Dead – When the thread finishes its execution i.E. The run() approach execution completes, it's miles stated to be in dead kingdom. A dead nation can not be started once more. If a begin() approach is invoked on a dead thread a runtime exception will occur.
Question 22. What Is Use Of Synchronized Keyword?
synchronized keyword can be implemented to static/non-static strategies or a block of code. Only one thread at a time can access synchronized techniques and if there are a couple of threads seeking to get right of entry to the same technique then different threads must watch for the execution of method by way of one thread. Synchronized keyword offers a lock at the item and as a result prevents race circumstance. E.G.
Public void synchronized technique()
public void synchronized staticmethod()
public void myMethod()
//synchronized key-word on block of code
Question 23. What Is The Difference When The Synchronized Keyword Is Applied To A Static Method Or To A Non Static Method?
When a synch non static method is called a lock is obtained at the object. When a synch static method is called a lock is acquired at the magnificence and now not on the object. The lock on the item and the lock on the class donâ€™t intervene with every different. It approach, a thread accessing a synch non static approach, then the other thread can access the synch static approach at the equal time however canâ€™t get entry to the synch non static approach.
Maven Interview Questions
Question 24. What Is A Volatile Keyword?
In preferred each thread has its personal reproduction of variable, such that one thread isn't concerned with the price of identical variable within the different thread. But someday this could now not be the case. Consider a state of affairs in which the be counted variable is conserving the number of times a method is called for a given elegance irrespective of any thread calling, in this situation regardless of thread get entry to the count number must be expanded so the count variable is asserted as risky.
The reproduction of volatile variable is saved within the most important reminiscence, so every time a thread access the variable even for studying cause the local copy is updated each time from the principle memory. The unstable variable additionally have overall performance troubles.
Core Java Interview Questions
Question 25. What Is The Difference Between Yield() And Sleep()?
yield() technique pauses the presently executing thread briefly for giving a danger to the last waiting threads of the equal precedence to execute. If there may be no waiting thread or all the waiting threads have a lower precedence then the identical thread will keep its execution. The yielded thread while it will get the hazard for execution is determined via the thread scheduler whose conduct is seller established. If does not launch the lock at the gadgets obtained.
Sleep() allows the thread to doze off nation for x milliseconds. When a thread is going into sleep nation it doesn’t releases the lock.
Java 8 Tutorial
Question 26. What Is The Difference Between Wait() And Sleep()?
wait() is a method of Object magnificence. Sleep() is a technique of Thread elegance.
Sleep() allows the thread to fall asleep nation for x milliseconds. When a thread is going into sleep country it doesn’t launch the lock. Wait() lets in thread to release the lock and goes to suspended country. The thread is best active whilst a notify() or notifAll() technique is referred to as for the equal item.
Java eight Interview Questions
Question 27. What Is Multithreading?
The manner of executing more than one threads concurrently is referred to as multithreading. Java supports multithreading. The primary gain of multithreading is reducing CPU idle time and improving the CPU utilization. This makes the job to be completed in much less time.
JSP Interview Questions
Question 28. What Is Starvation?
Starvation is a situation when some threads obtained the shared sources for long term and consequently different threads aren't capable of get right of entry to the ones resources and now not able to do something further.
For instance, suppose an item offers a synchronized method that regularly takes a long term to return.
If one thread invokes this technique frequently, different threads that still require frequent synchronized get admission to to that item could be blocked.
In Java, Starvation may be as a result of beside the point allocation of thread priorities.
A thread with low precedence can be starved by way of the threads of higher precedence if the better precedence threads do now not launch shared sources time to time.
Apache Ant Tutorial
Question 29. How Do You Debug Your Application For Issues When Multiple Threads Are Being Executed?
Following are a few manner to debug issues in multi-threaded packages in Java.
By using logging and print statements together with thread names. In this way we can realize approximately the waft of thread execution.
With the use of debugging capability available in Eclipse and JDeveloper.
We can write a thread sell off of the utility in an effort to deliver the facts about the lively threads at a point of time.
This is handiest manner for detecting deadlocks in manufacturing structures.
Apache Ant Interview Questions
Question 30. What Are The Methods Of The Thread Class Used To Schedule The Threads?
The techniques of the thread class used to time table the threads are as follows:
public very last void join() throws InterruptedException
public very last void notify()
public final void notifyAll()
public static void yield()
public very last void setPriority(int precedence)
public static void sleep(long millis) throws InterruptedException
public final void wait() throws InterruptedException
Question 31. Explain The Method Of Runnable Interface With Example.
In this approach of creating thread, we need to put in force the Runnable interface and implement the run() approach in our elegance.
We must create an object of our magnificence.
Then we you need to skip the reference of that item for creating a new object of Thread
Invoke the start approach the usage of this Thread item with a purpose to create a brand new thread of execution.
public class MyThread implements Runnable
public void run()
// code to execute beneath the thread
public static void most important(String  args)
MyThread c = new NewThread();
Thread t = new Thread(c);
Question 32. What Happens If We Invoke Run Method Without Calling The Start Method For A Thread Instance?
1.If we instantiate a thread it's far known as in new state till the Start() approach is known as.
2.If we do not name a start() method for that thread example, the thread isn't referred to as alive.
Three.If we invoke run approach without calling the begin technique for a thread instance, the code in run() method wil not be achieved by means of a brand new thread however it will be accomplished via the prevailing thread simplest.
Java Programmer Interview Questions
Question 33. What Is Thread Leak?
Thread leak is when software does now not release references of the thread object and those threads do now not get rubbish amassed.
Number of such unused threads will increase with time and it could reason problems in the software like long reaction time.
To conquer this hassle we will do the subsequent
1. By maintaining a log for all entry and go out factor of thread.
2. Check how the brand new thread is created and how it's far closed.
Three. By using exception coping with and many others.
Java-Springs Interview Questions
Question 34. Explain The Method Of Thread Class With Example.
In this technique of making thread, we ought to extend the Thread magnificence and override the run() method in our magnificence to create a Thread.
We need to create an object of the our elegance.
Once the object is created then we ought to invoke the start() technique and it's going to generate a new thread of execution.
public magnificence MyThread extends Thread
public void run()
// code to execute under the thread
public static void foremost(String  args)
MyThread c = new MyThread();
Question 35. What Is The Difference Between Yielding And Sleeping?
Sleep causes the presently executing thread to sleep till the desired time is completed. The thread will resume as soon as the required time period is over.
Sleep causes the currently executing thread to sleep and offers a danger to different threads to execute. The thread will be part of the geared up queue.
Thread.Sleep() will moves the thread to “Wait” state.
Thread.Yield() will actions the thread to “Ready” country.
Question 36. What Is The Difference Between Pre Emptive Scheduling And Time Slicing?
In Preemptive scheduling, highest precedence challenge will executes until it enters in ready or lifeless states. It additionally executes, till a higher priority mission enters.
In Time cutting, a mission will execute for a set time slice and after that it'll cross in equipped country.
At that point the scheduler will discover the executable project, consistent with the concern and numerous other duties.
In preemptive scheduling, the jogging venture will be preempted with the aid of the higher priority challenge.
In time slicing strategies, a venture executes till the required time frame. Once the execution of that venture is entire then the higher precedence venture can be executed if to be had.
JMS(Java Message Service) Interview Questions
Question 37. Can You Tell Some Ways In Which A Thread Can Enter The Waiting State?
A thread can input the ready country with the aid of the subsequent approaches:
We can invoke sleep() approach of the thread.
An try and acquire the object’s lock can placed the thread in ready mode.
We can also invoke wait() technique of the thread.
A thread can also be entered in ready kingdom by invoking its suspend() technique.
Question 38. Name The Methods Available In The Thread Class.
be a part of()
Question 39. What Is Time Slicing?
Timeslicing is the approach of allocating CPU time to character threads in a concern time table.
Question forty. Is It Possible To Perform Stream Operations In Java 8 With A Thread Pool?
Collections provide the method parallelStream() to create a movement this is processed by way of a thread pool. Alternatively you could call the intermediate technique parallel() on a given movement to convert a sequential move to a parallel counterpart.
Java applet Interview Questions
Question 41. How Can We Access The Thread Pool That Is Used By Parallel Stream Operations?
The thread pool used for parallel circulation operations may be accessed by means of ForkJoinPool.CommonPool(). This way we can question its stage of parallelism with commonPool.GetParallelism(). The degree can't be changed at runtime but it can be configured by using offering the subsequent JVM parameter: -Djava.Util.Concurrent.ForkJoinPool.Commonplace.Parallelism=five.
Question forty two. What Is The Difference Between Hashmap And Hashtable Particularly With Regard To Thread-protection?
The strategies of Hashtable are all synchronized. This isn't the case for the HashMap implementation. Hence Hashtable is thread-safe whereas HashMap isn't thread-safe. For single-threaded applications it's far consequently more efficient to use the “more moderen” HashMap implementation.
Java Interview Questions
Question forty three. Provide An Example Why Performance Improvements For Single-threaded Applications Can Cause Performance Degradation For Multi-threaded Applications.
A prominent example for such optimizations is a List implementation that holds the variety of elements as a separate variable. This improves the performance for single-threaded packages as the size() operation does not need to iterate over all elements but can go back the current wide variety of elements without delay. Within a multi-threaded utility the additional counter has to be guarded by using a lock as more than one concurrent threads can also insert elements into the listing. This additional lock can fee overall performance when there are extra updates to the list than invocations of the dimensions() operation.
Question 44. What Is The Purpose Of The Class Java.Lang.Threadlocal?
As reminiscence is shared among different threads, ThreadLocal provides a manner to keep and retrieve values for every thread one after the other. Implementations of ThreadLocal shop and retrieve the values for each thread independently such that after thread A stores the value A1 and thread B stores the value B1 within the identical instance of ThreadLocal, thread A in a while retrieves fee A1 from this ThreadLocal example and thread B retrieves fee B1.
Question forty five. What Are Possible Use Cases For Java.Lang.Threadlocal?
Instances of ThreadLocal may be used to move statistics in the course of the application with out the want to skip this from method to approach. Examples will be the transportation of security/login information inside an example of ThreadLocal such that it's miles handy by using every method. Another use case would be to transport transaction records or in wellknown items that should be handy in all techniques without passing them from technique to technique.