IQ-MultiThreads


  • What is multithreading?

          Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:

                   Threads share the same address space.
                   Thread is lightweight.
                   Cost of communication between process is low.
---------------------------


  • What is thread?

                 A thread is a lightweight subprocess.
            It is a separate path of execution.It is called separate path of execution because each thread runs in a separate stack frame.
---------------------------







  • What does join() method?

           The join() method waits for a thread to die.
           In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.
---------------------------


  • Can we start a thread twice?

              No. After starting a thread, it can never be started again.
              If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
---------------------------


  • Can we call the run() method instead of start() ?

             Yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.
             Each thread starts in a separate call stack.
Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
---------------------------


  • What is the difference between preemptive scheduling and time slicing ?

               Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.
               Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
---------------------------


  • What is difference between wait() and sleep() method ?

             - wait() method is defined in Object class. while sleep() method is defined in Thread class.
             - wait() method releases the lock. while sleep() method does not releases the lock.
---------------------------


  • What is daemon thread ?

               Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
               There are many java daemon threads running automatically e.g. gc, finalizer etc.

               You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc.

              Points to remember for Daemon Thread.

              It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
              Its life depends on user threads.
              It is a low priority thread.
---------------------------


  • What do you understand about Thread Priority ?

              Every thread has a priority, usually higher priority thread gets precedence in execution but it depends on Thread Scheduler implementation that is OS dependent.
              We can specify the priority of thread but it doesn’t guarantee that higher priority thread will get executed before lower priority thread.
              Thread priority is an int whose value varies from 1 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread
---------------------------


  • What is shutdown hook ?

              The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down. So we can use it perform clean up resource.
              The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else.
              So if you want to execute some code before JVM shuts down, use shutdown hook.

             The JVM shuts down when:
                     - user presses ctrl+c on the command prompt
                     - System.exit(int) method is invoked
                     - user logoff
                     - user shutdown etc.
---------------------------


  • What is context-switching in multi-threading ?

               Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time.
               Context Switching is the essential feature for multitasking operating system and support for multi-threaded environment.
---------------------------


  • How can we make sure main() is the last thread to finish in Java Program ?

                 We can use Thread join() method to make sure all the threads created by the program is dead before finishing the main function. Here is an article about Thread join method.
---------------------------


  • What is synchronization ?

             Synchronization is the capabilility of control the access of multiple threads to any shared resource.It is used:
                       - To prevent thread interference.
                       - To prevent consistency problem.
---------------------------


  • What is the purpose of Synchronized block ?

                 Synchronized block is used to lock an object for any shared resource.
                 Scope of synchronized block is smaller than the method.
---------------------------


  • What is the difference between notify() and notifyAll() ?

               The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.
---------------------------


  • How does thread communicate with each other ?

              When threads share resources, communication between Threads is important to coordinate their efforts.
             Object class wait(), notify() and notifyAll() methods allows threads to communicate about the lock status of a resource.
---------------------------


  • What is deadlock ?

             Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.
---------------------------


  • How can we achieve thread safety in Java ?

            There are several ways to achieve thread safety in java
            synchronization, atomic concurrent classes, implementing concurrent Lock interface, using volatile keyword, using immutable classes and Thread safe classes.
---------------------------


  • Why Thread sleep() and yield() methods are static ?

              Thread sleep() and yield() methods work on the currently executing thread.
              So there is no point in invoking these methods on some other threads that are in wait state.
              That’s why these methods are made static so that when this method is called statically, it works on the current executing thread and avoid confusion to the programmers who might think that they can invoke these methods on some non-running threads.
---------------------------


  • Which is more preferred, Synchronized method or Synchronized block ?

              Synchronized block is more preferred way because it doesn’t lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.
---------------------------


  • What is volatile keyword in Java ?

               When we use volatile keyword with a variable, all the threads read it’s value directly from the memory and don’t cache it.
              This makes sure that the value read is the same as in the memory.
---------------------------


  • What is ThreadLocal ?

              Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
             Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.
---------------------------


  • What is Java Thread Dump, How can we get Java Thread dump of a Program ?

               Thread dump is list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump, Using Profiler, Kill -3 command, jstack tool etc.
               jstack is common tool to generate thread dump of a program because it’s easy to use and comes with JDK installation.



No comments:

Post a Comment

Home

Mastering Java Interview Questions: Your Comprehensive Guide         If you're preparing for a Java interview or just lookin...