Friday, 12 October 2018

Multi-threading Interview Questions Java


  1. How Volatile in Java works?
    1. The Java volatile keyword cannot be used with method or class and it can only be used with a variable.
    2. Java volatile keyword also guarantees visibility and ordering and write to any volatile variable happens before any read into the volatile variable.
    3. Example: Singleton Class 
      1. public class Singleton{ private static volatile Singleton _instance; //volatile variable public static Singleton getInstance(){ if(_instance == null){ synchronized(Singleton.class){ if(_instance == null) _instance = new Singleton(); } } return _instance; }
      2. writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java, this is handled by Java himself and such updates will be visible by all reader threads.
    4. If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable.
    5. Both T1 and T2 can refer to a class containing this variable. You can then make this variable volatile, and this means that changes to that variable are immeditately visible in both threads.
    6. public class App { public static volatile boolean isEven = true; public static void main(String[] args) { Object mutex = new Object(); Thread odd = new Thread(new Runnable() { @Override public void run() { try { int i = 0; while (i < 20) { synchronized (mutex) { if (isEven) { mutex.wait(); } System.out.println("Odd"); isEven = true; mutex.notify(); } i++; } } catch (Exception e) { e.printStackTrace(); } } }); Thread even = new Thread(new Runnable() { @Override public void run() { try { int i = 0; while (i < 20) { synchronized (mutex) { if (!isEven) { mutex.wait(); } System.out.println("Even"); isEven = false; mutex.notify(); } i++; } } catch (Exception e) { e.printStackTrace(); } } }); odd.start(); even.start(); } }
    7. Volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.
    8. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).
    9. Using the volatile keyword in Java on variables reduces the risk of memory consistency errors because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.
    10. Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.
  2. How is CountDownLatch used in Java Multithreading?
    1. CountDownLatch works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch.
    2. Any thread, usually the main thread of the application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another thread. 
    3. All other threads are required to count down by calling CountDownLatch.countDown() once they are completed or ready.
    4. As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch is that it's not reusable: once count reaches zero you cannot use CountDownLatch any more.
  3. can we make array volatile in java?
    1. Yes, you can make an array (both primitive and reference type array e.g. an int array and String array) volatile in Java
    2. But declaring an array volatile does NOT give volatile access to it's fields. you're declaring the reference itself volatile, not it's elements.
      1. protected volatile int[] primes = new int[10];
        1. then if you assign a new array to primes variable, change will be visible to all threads, but changes to individual indices will not be covered under volatile guarantee i.e
      2. primes = new int[20];
        1. will follow the "happens-before" rule and cause memory barrier refresh visible to all threads
      3. primes[0] = 10;
        1.  will not visible changes in all threads
    3. Same for collections also
    4. In other words you're declaring a volatile set of elements, not a set of volatile elements. The solution here is to use AtomicIntegerArray in case you want to use integers
  4.  Thread Local?
    1. The ThreadLocal class in Java enables you to create variables that can only be read and writte by the same thread
    2. private ThreadLocal myThreadLocal = new ThreadLocal();
    3. Now you can only store strings in the ThreadLocal instance.
    4. myThreadLocal.set("Hello ThreadLocal"); String threadLocalValue = myThreadLocal.get();
  5. How immutable objects manage memory ?
    1. The advantage we get with String is that a common pool of string literals is kept by the virtual machine stopping the Heap getting filled up . The reasoning behind this is that much of the memory of a program can be taken up with storing commonly used strings.
  6. How to throw exceptions from Runnable.run?
    1. Do not use Runnable interface from Thread library, but instead create your own interface with the modified signature that allows checked exception to be thrown
    2. public interface MyRunnable { void myRun ( ) throws MyException; }
    3. You may even create an adapter that converts this interface to real Runnable ( by handling checked exception ) suitable for use in Thread framework.
  7. Difference Between Daemon and User Threads?
    1. Java offers two types of threads: user threads and daemon threads.
    2. JVM will wait for all active user threads to finish their execution before it shutdown itself.
    3. Daemon thread doesn't get that preference, JVM will exit and close the Java program even if there is a daemon thread running in the background
    4.  Daemon threads are low-priority threads whose only role is to provide services to user threads..
    5. A daemon thread is a thread that does not prevent the JVM from exiting when the user thread finishes but the thread is still running. An example for a daemon thread is the garbage collection.
    6. That’s why infinite loops, which typically exist in daemon threads, will not cause problems, because any code, including the finally blocks, won’t be executed once all user threads have finished their execution. For this reason, daemon threads are not recommended for I/O tasks.
    7. // Java program to demonstrate the usage of // setDaemon() and isDaemon() method. public class DaemonThread extends Thread { public DaemonThread(String name){ super(name); } public void run() { // Checking whether the thread is Daemon or not if(Thread.currentThread().isDaemon()) { System.out.println(getName() + " is Daemon thread"); } else { System.out.println(getName() + " is User thread"); } } public static void main(String[] args) { DaemonThread t1 = new DaemonThread("t1"); DaemonThread t2 = new DaemonThread("t2"); DaemonThread t3 = new DaemonThread("t3"); // Setting user thread t1 to Daemon t1.setDaemon(true); // starting first 2 threads t1.start(); t2.start(); // Setting user thread t3 to Daemon t3.setDaemon(true); t3.start(); } } ######OUT PUT#### t1 is Daemon thread t2 is User thread

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *