Thread Creation and Management

1. Basic Threading Concepts

Thread Creation Methods

  1. Extending Thread class

javaCopyclass MyThread extends Thread {
    public void run() {
        // thread code here
    }
}
// Usage
MyThread thread = new MyThread();
thread.start();
  1. Implementing Runnable interface

javaCopyclass MyRunnable implements Runnable {
    public void run() {
        // thread code here
    }
}
// Usage
Thread thread = new Thread(new MyRunnable());
thread.start();
  1. Anonymous Runnable

javaCopyThread thread = new Thread(new Runnable() {
    public void run() {
        // thread code here
    }
});
  1. Lambda Expression (Java 8+)

javaCopyThread thread = new Thread(() -> {
    // thread code here
});

Thread Lifecycle

  • NEW: Thread object created but not yet started

  • RUNNABLE: Thread executing in JVM

  • BLOCKED: Waiting for monitor lock

  • WAITING: Waiting indefinitely for another thread

  • TIMED_WAITING: Waiting for specified time

  • TERMINATED: Thread completed execution

Basic Thread Methods

javaCopythread.start();     // Start thread execution
thread.run();       // Run thread code (don't call directly)
thread.sleep(1000); // Sleep for 1000ms
thread.join();      // Wait for thread completion
thread.interrupt(); // Interrupt thread
thread.isAlive();   // Check if running
thread.setPriority(Thread.MAX_PRIORITY); // Set priority

2. Intermediate Concepts

Thread Synchronization

  1. synchronized keyword

javaCopy// Method level
synchronized void method() {
    // synchronized code
}

// Block level
synchronized(object) {
    // synchronized code
}
  1. volatile keyword

javaCopyprivate volatile boolean flag = false;
  1. Object-level locking

javaCopyprivate final Object lock = new Object();
public void method() {
    synchronized(lock) {
        // synchronized code
    }
}

Thread Communication

javaCopy// Wait and Notify
synchronized(object) {
    while(condition) {
        object.wait();
    }
    // do something
    object.notify();
}

Thread Pool

javaCopy// Fixed Thread Pool
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
    // task code
});

// Cached Thread Pool
ExecutorService executor = Executors.newCachedThreadPool();

// Scheduled Thread Pool
ScheduledExecutorService scheduler = 
    Executors.newScheduledThreadPool(1);

3. Advanced Concepts

Lock Interface

javaCopyprivate final ReentrantLock lock = new ReentrantLock();

public void method() {
    lock.lock();
    try {
        // critical section
    } finally {
        lock.unlock();
    }
}

ReadWriteLock

javaCopyprivate final ReadWriteLock rwLock = new ReentrantReadWriteLock();

public void read() {
    rwLock.readLock().lock();
    try {
        // read operation
    } finally {
        rwLock.readLock().unlock();
    }
}

Atomic Classes

javaCopyprivate AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // Thread-safe increment

CompletableFuture (Java 8+)

javaCopyCompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> "Result")
    .thenApply(s -> s + " processed")
    .thenAccept(System.out::println);

ThreadLocal

javaCopyprivate ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
threadLocal.set(value);
Integer value = threadLocal.get();

4. Common Interview Questions

  1. What is thread safety?

    • Thread safety ensures that code behaves correctly when accessed by multiple threads simultaneously

    • Achieved through synchronization, atomic operations, immutable objects

  2. Difference between process and thread?

    • Process: Independent execution unit with its own memory space

    • Thread: Lightweight unit sharing process memory space

  3. What is deadlock?

    • Situation where two or more threads are blocked forever, waiting for each other

javaCopy// Deadlock example
synchronized(lockA) {
    synchronized(lockB) {
        // Thread 1 code
    }
}
// Meanwhile in another thread
synchronized(lockB) {
    synchronized(lockA) {
        // Thread 2 code
    }
}
  1. How to prevent deadlock?

    • Lock ordering

    • Lock timeouts

    • Deadlock detection

    • Using tryLock()

  2. Difference between wait() and sleep()?

    • wait() releases lock, sleep() doesn't

    • wait() called on Object, sleep() called on Thread

    • wait() needs synchronization, sleep() doesn't

  3. What is thread dumping?

    • Snapshot of the state of all threads in JVM

    • Used for debugging threading issues

    • Can be generated using jstack tool

  4. Explain the producer-consumer problem

javaCopyclass Buffer {
    private Queue<Integer> queue = new LinkedList<>();
    private int size;

    public synchronized void produce(int item) throws InterruptedException {
        while(queue.size() == size) {
            wait();
        }
        queue.add(item);
        notify();
    }

    public synchronized int consume() throws InterruptedException {
        while(queue.isEmpty()) {
            wait();
        }
        int item = queue.remove();
        notify();
        return item;
    }
}

5. Best Practices

  1. Always release locks in finally block

  2. Avoid using Thread.stop() (deprecated)

  3. Minimize synchronized scope

  4. Prefer concurrent collections over synchronized collections

  5. Use thread pools instead of creating threads manually

  6. Handle InterruptedException properly

  7. Avoid using Thread.sleep() in production code

  8. Use atomic classes for simple counters

  9. Implement proper exception handling in threads

  10. Use thread-safe collections when needed (ConcurrentHashMap, CopyOnWriteArrayList)

6. Common Threading Problems

  1. Race Conditions

  2. Memory Visibility Issues

  3. Deadlocks

  4. Livelocks

  5. Thread Starvation

  6. Priority Inversion

7. Debugging Tips

  1. Use Thread.currentThread().getStackTrace()

  2. Enable thread debugging in IDE

  3. Use jstack for thread dumps

  4. Monitor thread states

  5. Use logging in critical sections

  6. Use Java Flight Recorder for detailed analysis

Last updated