AZK CP Java Thread Interview Questions

  1. Difference between green thread and native thread in Java?
    • Green threads are scheduled by a virtual machine
    • Native threads are scheduled by a operational system.
  2. Why does thread named as green and native?
    • "Green" is earlier JVM threads project code-name. It is name of library, which provided VM-scheduled threads in Java 1.1
    • Native threads called so because they're belong to native platform
  3. What is Process? (4)
    • - typically independed
    • - has considerably more state information
    • - separate address spaces
    • - interact only through system IPC
    •       - IPC - interprocess communication - refers specifically to the mechanisms an operating system provides to allow processes it manages to share data
  4. What is Thread? (30)
    • - subsets of a process
    • - multiple threads w/i a process share process state, memory, ect
    • - threads share their address space
  5. Difference between thread and process?
    • 1) A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process.
    • 2) Java runtime environment runs as a single process which contains different classes and programs as processes ("heavyweight" tasks) basically the execution of applications. Thread can be called "lightweight" process
    • 3) Thread requires less resources to create and exists in the process. Threads within the same process share the process resources and the same address space whereas different processes do not.
  6. What is context switching in multi-threading?
    A context switch (also sometimes referred to as a process switch or a task switch) is the switching of the CPU (central processing unit) from one process or thread to another. A process (also sometimes referred to as a task) is an executing (i.e., running) instance of a program.
  7. CPU
    central processing unit
  8. IPC
    • - interprocess communication - refers specifically to the mechanisms
    • an operating system provides to allow processes it manages to share
    • data
  9. Deadlock
    describes a situation where two or more threads are blocked forever, waiting for each other
  10. LiveLock
    looks like a deadlock in the sense that two (or more) processes are blocking each others. But with the livelock, each process is waiting “actively”, trying to resolve the problem on its own (like reverting back its work and retry). A live lock occurs when the combination of these processes’s efforts to resolve the problem makes it impossible for them to ever terminate.
  11. Starvation
    occurs when one or more threads in your program are blocked from gaining access to a resource and, as a result, cannot make progress.
  12. Difference between deadlock and livelock, deadlock and starvation?
    • A livelock is similar to a deadlock, except that the states of the processes involved in The livelock constantly change with regard to one another, none progressing.
    • Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing.
  13. What thread-scheduling algorithm is used in Java?
    • The JVM schedules using a preemptive, priority-based scheduling algorithm.
    • All Java threads have a priority and the thread with the highest priority is scheduled to run by the JVM.
    • In case two threads have the same priority, a FIFO ordering is followed.
  14. What is thread-scheduler in Java?
    An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution.
  15. What is thread-group?
    • A thread group represents a set of threads. In addition, a thread group  can also include other thread groups. The thread groups form a tree in  which every thread group except the initial thread group has a parent.
    • A thread is allowed to access information about its own thread group, but not to access information about its thread group's parent thread group  or any other thread groups
    • Every Java thread is a member of a thread group. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. For example, you can start or suspend all the threads within a group with a single method call.
  16. What is ThreadGroup?
    Why it’s advised not to use it?
    • java.lang.ThreadGroup is a class which was intended to provide information about a thread group.
    • ThreadGroup API is weak and it doesn’t have any functionality that is  not provided by Thread. Two of the major feature it had are to get the  list of active threads in a thread group and to set the uncaught  exception handler for the thread.
    • Java 1.5 has added setUncaughtExceptionHandler(UncaughtExceptionHandler eh) method using which we can add uncaught exception handler to the thread.
    • So ThreadGroup is obsolete and hence not advised to use anymore
  17. What are the benefits of multi-threaded programming?
    • In Multi-Threaded programming, multiple threads are executing concurrently that improves the performance because CPU is not idle in case some thread is waiting to get some resources.
    • Multiple threads share the heap memory, so it’s good to create multiple threads to execute some task rather than creating multiple processes.
    • For example, Servlets are better in performance than CGI because Servlet support multi-threading but CGI doesn’t.
  18. What is difference between user Thread and daemon Thread?
    • When we create a Thread in java program, it’s known as user thread.
    • A daemon thread runs in background and doesn’t prevent JVM from terminating.
    • When there are no user threads running, JVM shutdown the program and quits. A child thread created from daemon thread is also a daemon thread.
  19. How can we create a Thread in Java?
    • 1) By implementing Runnable interface and then creating a Thread object from it
    • 2) Extend the Thread Class.
  20. What are different states in lifecycle of Thread?
    • 1) New - When we create a Thread in java program
    • 3) Runnable - we start the thread (Thread Scheduler allocating CPU)
    • 2) Running - as soon as it gets CPU time
    • 4) Suspended - temporary halt to its execution
    • 5) Resumed
    • 6) Blocked - when waiting for a resource
    • 7) Terminated - its execution ends and cannot be resumed

    Thread Scheduler is responsible to allocate CPU to threads in Runnable thread pool and change their state to Running.
  21. Why we call start() method which in turns calls run() method, why not we directly call run() method ?
    • - when you call start() method it creates new Thread and execute code declared in run()
    • - directly calling run() method doesn’t create any new Thread and execute code on same calling thread
  22. Can we call run() method of a Thread class?
    Yes, we can call run() method of a Thread class, but then it will behave like a normal method. To actually execute it in a Thread, we need to start it using Thread.start() method.
  23. How can we pause the execution of a Thread for specific time?
    • We can use Thread class sleep() method to pause the execution of Thread for certain time.
    • Note that this will not stop the processing of thread for specific time, once the thread awake from sleep, it’s state gets changed to runnable and based on thread scheduling, it gets executed.
  24. 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.
  25. What is Thread Scheduler?
    • Thread Scheduler is the Operating System service that allocates the CPU time to the available runnable threads.
    • Once we create and start a thread, it’s execution depends on the implementation of Thread Scheduler.
    • Thread scheduling can’t be controlled by java, so it’s always better to control it from application itself
  26. What is Time Slicing?
    • Time Slicing is the process to divide the available CPU time to the available runnable threads.
    • Allocation of CPU time to threads can be based on thread priority or the thread waiting for longer time will get more priority in getting CPU time.
  27. 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.
  28. 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.
  29. How does thread communicate with each other?
    Object class wait(), notify() and notifyAll() methods allows threads to communicate about the lock status of a resource.
  30. Why thread communication methods wait(), notify() and notifyAll() are in Object class?
    • In Java every Object has a monitor and wait, notify methods are used to wait for the Object monitor or to notify other threads that Object monitor is free now.
    • There is no monitor on threads in java and synchronization can be used with any Object, that’s why it’s part of Object class so that every class in java has these essential methods for inter thread communication.
  31. Why wait(), notify() and notifyAll() methods have to be called from synchronized method or block?
    • When a Thread calls wait() on any Object, it must have the monitor on the Object that it will leave and goes in wait state until any other thread call notify() on this Object.
    • Similarly when a thread calls notify() on any Object, it leaves the monitor on the Object and other waiting threads can get the monitor on the Object.
    • Since all these methods require Thread to have the Object monitor, that can be achieved only by synchronization, they need to be called from synchronized method or block.
  32. Why Thread sleep() and yield() methods are static?
    • static void sleep(long millis)
    •    - Causes the currently executing thread to sleep for the specified number of milliseconds
    • static void yield()
    •    - A hint to the scheduler that the current thread is willing to yield
    • its current use of a processor.

    • 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.
  33. How can we achieve thread safety in Java? (5)
    • 1) synchronization
    • 2) atomic concurrent classes
    • 3) implementing concurrent Lock interface
    • 4) using volatile keyword
    • 5) using immutable classes and Thread safe classes
  34. 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.
  35. 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.
  36. How to create daemon thread in Java?
    • Thread class setDaemon(true) can be used to create daemon thread in java.
    • We need to call this method before calling start() method else it will throw IllegalThreadStateException
  37. What is ThreadLocal?
    • java.lang.ThreadLocal<T>
    • public class ThreadLocal<T>
    • 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.
  38. 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.
    • I prefer jstack tool to generate thread dump of a program because it’s easy to use and comes with JDK installation. Since it’s a terminal based tool, we can create script to generate thread dump at regular intervals to analyze it later on.
  39. What is Deadlock? How to analyze and avoid deadloc?
    • Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources.
    • To analyze a deadlock:
    •    - we need to look at the java thread dump of the application
    •    - we need to look out for the threads with state as BLOCKED
    •    - and then the resources it’s waiting to lock
    • Every resource has a unique ID using which we can find which thread is already holding the lock on the object.
    • To avoid deadlock situation:
    •    - Avoid Nested Locks
    •    - Lock Only What is Required
    •    - Avoid waiting indefinitely
  40. What is Java Timer Class? How to schedule a task to run after specific interval?
    • java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future.
    • Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
    • java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.
  41. What is Thread Pool? How can we create Thread Pool in Java?
    • A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.
    • java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java
  42. What will happen if we don’t override Thread class run() method?
    If we create an instance of Thread class as new TestThread(), it’s set to null. So nothing will happen if we don’t override the run() method

    • Example:
    • public void run() {
    •     if (target != null) {
    •     }

    • public class TestThread extends Thread {
    •           //not overriding method
    •           //main method, can be in other class too
    •     public static void main(String args[]){
    •        Thread t = new TestThread();
    •        System.out.println("Before starting thread");
    •        t.start();
    •        System.out.println("After starting thread");
    •     }
    • }

    It will print only below output and terminate.
  43. What is atomic operation? What are atomic classes in Java Concurrency API?
    • Atomic operations
    •    - are performed in a single unit of task without interference from other operations
    •    - this means that NO lock or other synchronization mechanism is required
    • Atomic operations
    •    - are necessity in multi-threaded environment to avoid data inconsistency
    •    - are accomplished through the use of classes, such as:
    •       - AtomicInteger
    •       - AtomicLong
    •    - and methods such as:
    •       - get( )
    •       - set( )
    •       - compareAndSet( )
    •       - decrementAndGet( )
    •       - getAndSet( )
  44. What is Lock interface in Java Concurrency API?
    What are it’s benefits over synchronization?
    • Lock interface
    •    - provide more extensive locking operations than can be obtained using synchronized methods and statements.
    •    - allow more flexible structuring
    •    - may have quite different properties
    •    - may support multiple associated Condition objects.
    • The advantages of a lock are:
    •    1) it’s possible to make them fair
    •    2) it’s possible to make a thread responsive to interruption while waiting on a Lock object.
    •    3) it’s possible to try to acquire the lock, but return immediately or after a timeout if the lock can’t be acquired
    •    4) it’s possible to acquire and release locks in different scopes, and in different orders
  45. What is Executors Framework?
    In Java 5, Executor framework was introduced with the java.util.concurrent.Executor interface.

    • The Executor framework is a framework for:
    •    - standardizing invocation
    •    - scheduling
    •    - execution
    •    - control
    • of asynchronous tasks according to a set of execution policies.

    • Creating a lot many threads with no bounds to the maximum threshold can cause application to run out of heap memory.
    • So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused
    • Executors framework facilitate process of creating Thread pools in java.
  46. What is BlockingQueue?
    How can we implement Producer-Consumer problem using Blocking Queue?
    • java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element
    • BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue
    • BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.
    • BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem.
  47. What is Callable and Future?
    • Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
    • Callable interface use Generic to define the return type of Object.
    • Executors class provide useful methods to execute Callable in a thread pool.
    • Since callable tasks run in parallel, we have to wait for the returned Object.
    • Callable tasks return java.util.concurrent.Future object.
    • Using Future we can find out the status of the Callable task and get the returned Object.
    • It provides get() method that can wait for the Callable to finish and then return the result.
  48. What is FutureTask Class?
    • java.util.concurrent.FutureTask<V> is the base implementation class of Future interface and we can use it with Executors for asynchronous processing.
    • Most of the time we don’t need to use FutureTask class but it comes real handy if we want to override some of the methods of Future interface and want to keep most of the base implementation.
    • We can just extend this class and override the methods according to our requirements
  49. What are Concurrent Collection Classes?
    • Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the will throw ConcurrentModificationException.
    • Concurrent Collection classes support full concurrency of retrievals and adjustable expected concurrency for updates.
    •         Major classes are:
    •            - ConcurrentHashMap
    •            - CopyOnWriteArrayList
    •            - CopyOnWriteArraySet
  50. What is Executors Class?
    • Executors class provide utility methods for classes:
    •            - Executor
    •            - ExecutorService
    •            - ScheduledExecutorService
    •            - ThreadFactory
    •            - Callable
    • Executors class can be used to easily create Thread Pool in java
    • Executors class is the only class supporting execution of Callable implementations.
  51. What are some of the improvements in Concurrency API in Java 8?
    • Some important concurrent API enhancements are:
    •            1) ConcurrentHashMap class
    •               - A hash table supporting full concurrency of retrievals and
    •         high expected concurrency for updates.
    •               - This class obeys the
    •         same functional specification as Hashtable, and
    •         includes versions of methods corresponding to each method of
    •         Hashtable.
    •               ConcurrentHashMap methods -
    •                  - compute()
    •                  - forEach()
    •                  - forEachEntry()
    •                  - forEachKey(),
    •                  - forEachValue()
    •                  - merge()
    •                  - reduce()
    •                  - search()
    •            2) CompletableFuture
    •               - that may be explicitly completed (setting its value and status).
    •            3) Executors newWorkStealingPool() method
    •            - to create a work-stealing thread pool using all available processors as its target parallelism level.
  52. You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
    it can be achieved by using join() method of Thread class.
  53. What is the advantage of new Lock interface over synchronized block in Java?
    The major advantage of Lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and Conditional Blocking.
  54. What are differences between wait() and sleep() method in java?
    • wait():
    •    - release the lock or monitor.
    •    - is used for inter-thread communication
    • sleep():
    •    - doesn't release any lock or monitor while waiting
    •    - is used to introduce pause on execution
  55. What is race condition?
    • - occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other
    • - Prevention: careful programming that properly synchronizes access to shared resources
  56. How will you find and solve race condition?
    • - since readability of Java code is very good and synchronized constructs are well defined heaps to find race conditions by code review
    • - finding race conditions by unit testing is not reliable due to random nature of race conditions
  57. How will you awake a blocked thread in java?
    • - if thread is blocked on IO then it is NOT a way to interrupt the thread
    • - if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing InterruptedException
  58. What is difference between CyclicBarriar and CountdownLatch in Java ?
    • CountDownLatch
    •    - java.util.concurrent key feature synchronizer
    •    - thread will wait until a specified number of events have occurred
    • CyclicBarrier
    •    - java.util.concurrent key feature synchronizer
    •    - enables a group of threads to wait at a predefined execution point.
    • One difference is:
    •    - that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch.
  59. What is immutable object?
    it cannot be changed once it's created
  60. Why String is Immutable or Final in Java?
    • - Immutable object cannot be changed once it's created.
    • - String objects are cached in String pool and cached String literals are shared between multiple clients.
    • - String is Immutable in Java to avoid risk, where one client's action would affect all another client.
    • - At the same time, String was made final so that no one can compromise invariant of String class by extending and overriding behaviors.
  61. What are some common problems you have faced in multi-threading environment? (5)
    • 1) memory-interference
    • 2) race conditions
    • 3) deadlock
    • 4) live lock
    • 5) starvation
Card Set
AZK CP Java Thread Interview Questions
AZK CP Java Thread Interview Questions