mutex VS. Semaphore

  • mutext is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.

    Officially: "Mutexes are typically used to serialise access to a
    section of  re-entrant code that cannot be executed concurrently
    by more than one thread. A mutex object only allows one thread
    into a controlled section, forcing other threads which attempt to
    gain access to that section to wait until the first thread has
    exited from that section."
    
    (A mutex is really a semaphore with value 1.)
    
  • Semaphore is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.
    Officially: "A semaphore restricts the number of simultaneous
    users of a shared resource up to a maximum number. Threads can
    request access to the resource (decrementing the semaphore), and
    can signal that they have finished using the resource
    (incrementing the semaphore)."
    
    What is volatile keyword?
  • The Java volatile keyword is used to mark that every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.
  • Java Volatile Keyword

What is ThreadLocal?

  • The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.
  • Java ThreadLocal

What is Race Condition? What is Critical Section?

  • Where two or more threads compete for the same resource, where the sequence in which the resource is accessed is significant, is called race conditions.
  • A code section that leads to race conditions is called a critical section.
  • Race Conditions and Critical Sections

Does each thread has its own thread stack?

  • Yes each thread has its own call stack. For eg:

          Thread t1 = new Thread();
          Thread t2 = new Thread();
          Thread t3 = t1;
    

    In the above example t1 and t3 will have the same stack and t2 will have its own independent stack.

What are the methods of the thread class used to schedule the threads?

  • public static void sleep(long millis) throws InterruptedException
  • public static void yield()
  • public final void join() throws InterruptedException
  • public final void setPriority(int priority)
  • public final void wait() throws InterruptedException
  • public final void notify()
  • public final void notifyAll()

Can static methods be synchronized? Can two threads call two different static synchronized methods of the same class? Does a static synchronized method block a non-static synchronized method?

  • Yes. Static methods are class methods and have only one copy of static data for the class, only one lock for the entire class is required. Every class in java is represented by java.lang.Class instance. The lock on this instance is used to synchronize the static methods.
  • No. The static synchronized methods of the same class always block each other as only one lock per class exists.So no two static synchronized methods can execute at the same time.
  • No, the thread executing the static synchronized method holds a lock on the class and the thread executing the non-satic synchronized method holds the lock on the object on which the method has been called, these two locks are different and these threads do not block each other.

Can a thread hold multiple locks at the same time? Can a thread call multiple synchronized methods on the object of which it hold the lock?

  • Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock and enters into the synchronized method / block, it may call another synchronized method and acquire a lock on another object.
  • Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that same object using the lock that it already holds. The locks are Reentarant.

Can the variables or classes be Synchronized?

  • No. Only methods can be synchronized.

How many locks does an object have?

  • Each object has only one lock.

What are the daemon threads?

  • Daemon thread are service provider threads run in the background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the JVM exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution.
  • To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method.
  • Example of the Daemon thread is the Garbage Collector run by JVM to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution.
  • 守护线程总结

What is difference between notify() and notfiyAll()?

  • notify() wakes up the first thread that called wait() on the same object.
  • notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will run first.

What is the difference between yield(), wait() and sleep()?

  • yield() allows the current the thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority.
  • wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.
  • sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t releases the lock.

Can constructors be synchronized in Java?

  • No, constructors can not be synchronized in Java. In fact using the keyword “synchronized” with a constructor is actually a syntax error.

What’s a deadlock ? How do you ensure that N threads can access N resources without deadlock ?

  • A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly.
  • A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the mutexes in the same order, no deadlocks can arise. Java - Thread Deadlock

What is the difference between a synchronized method and a synchronized block ?

  • If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized block.
  • If you use the synchronized keyword on the method declaration, it will synchronize the whole method to the object or class.
  • Stack Overflow 1
  • Stack Overflow 2

Explain the available thread states in a high-level.

  • NEW: The thread becomes ready to run, but does not necessarily start running immediately.
  • RUNNABLE: The Java Virtual Machine (JVM) is actively executing the thread’s code.
  • BLOCKED: The thread is in a blocked state while waiting for a monitor lock.
  • WAITING: The thread waits for another thread to perform a particular action.
  • TIMED_WAITING: The thread waits for another thread to perform a particular action up to a specified waiting time.
  • TERMINATED: The thread has finished its execution.
  • java 线程的几种状态

Explain different ways of creating a thread. Which one would you prefer and why ?

  • There are three ways:
    • Class may extend the "Thread" class.
    • A class may implement the "Runnable" interface.
    • An application can use the "Executor" framework, in order to create a thread pool.
  • The "Runnable" interface is preferred, as it does not require an object to inherit the Thread class(extending the Thread class means that the subclass cannot extend any other class). In case your application design requires multiple inheritance, only interfaces can help you.

What is the difference between processes and threads ?

  • A thread has its own stack but shared heap.
  • A process is an execution of a program.
  • A Thread is a single execution sequence within a process.
  • Threads run in a shared memory space, while processes run in separate memory spaces.
  • A process can contain multiple threads. A Thread is sometimes called a lightweight process.

How to create thread-safe Singleton in Java?

public class Singleton{
    private static final Singleton INSTANCE = new Singleton();

    //make the constructor private so that this class cannot be instantiated
    private Singleton(){

    }

    public static Singleton getInstance(){
        return INSTANCE;
    }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}

How to make a method thread-safe in Java?

  • Adding synchronized to this method will makes it thread-safe.
class MyCounter {
    private static int counter = 0;

    public static synchronized int getCount() {
        return counter++;
    }
}
  • Using AtomicInteger from the package "java.util.concurrent.atomic".
import java.util.concurrent.atomic.AtomicInteger;

public class MyCounter {
    private static AtomicInteger counter = new AtomicInteger(0);

    public static int getCount() {
        return counter.getAndIncrement();
    }
}