Skip to Content
bytegarden

Multithreading

Thread Basics

  • Multithreading allows concurrent execution of multiple parts of a program
  • Each thread represents an independent path of execution
  • Threads share the same memory space and resources

Thread Lifecycle

  1. New: Thread is created but not yet started
  2. Runnable: Thread is ready for execution and scheduled
  3. Running: Thread is currently executing
  4. Blocked/Waiting: Thread is temporarily inactive (waiting for I/O or another thread)
  5. Terminated: Thread has completed its execution

Creating Threads

Using Thread Class

class MyThread extends Thread {
    public void run() {
        // Code to be executed in thread
    }
}

// Usage
MyThread thread = new MyThread();
thread.start();

Using Runnable Interface

class MyRunnable implements Runnable {
    public void run() {
        // Code to be executed in thread
    }
}

// Usage
Thread thread = new Thread(new MyRunnable());
thread.start();

Thread Methods

  1. start() - Begins thread execution
  2. sleep(long millis) - Pauses thread for specified milliseconds
  3. join() - Waits for thread to die
  4. yield() - Suggests thread to pause and let others execute

Thread Synchronization

  • Prevents multiple threads from accessing shared resources simultaneously
  1. Example using synchronized keyword:

    synchronized void method() {
        // Only one thread can execute this at a time
    }
    
    // OR
    
    synchronized(object) {
        // Synchronized block
    }
  2. Example using Locks:

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    class Counter {
        private Lock lock = new ReentrantLock();
        private int count = 0;
    
        void increment() {
            lock.lock();
            try {
                count++;
            } finally {
                lock.unlock();
            }
        }
    }

3, Example using wait() and notify():

 class SharedResource {
   synchronized void consume() {
     while (/* condition */) {
         wait();
     }
     // Consume resource
     notify();
   }

   synchronized void produce() {
     // Produce resource
     notify();
   }
 }

Thread Pool

  • Manages and reuses threads
  • Improves performance by reducing thread creation overhead
  • Example
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(new Task());

Common Issues

Deadlock

  • Deadlock occurs when two or more threads are blocked forever, waiting for each other

  • Prevention:

    1. Lock ordering
    2. Timeout mechanisms
    3. Deadlock detection
  • Example:

    class DeadlockExample {
      private Object lock1 = new Object();
      private Object lock2 = new Object();
      
      void method1() {
          synchronized(lock1) {
              synchronized(lock2) {
                  // Method code
              }
          }
      }
      
      void method2() {
          synchronized(lock2) {
              synchronized(lock1) {
                  // Method code
              }
          }
      }
    }
  • For another example, see this code (DeadlockExample.java, below)

    DeadlockExample.java
    class DeadlockExample {
        private Object lock1 = new Object();
        private Object lock2 = new Object();
        
        void method1() {
            System.out.println("Thread 1: Attempting to acquire lock1");
            synchronized(lock1) {
                System.out.println("Thread 1: Acquired lock1");
                try {
                    Thread.sleep(100); // Delay to ensure deadlock
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 1: Attempting to acquire lock2");
                synchronized(lock2) {
                    System.out.println("Thread 1: Acquired lock2");
                }
            }
        }
        
        void method2() {
            System.out.println("Thread 2: Attempting to acquire lock2");
            synchronized(lock2) {
                System.out.println("Thread 2: Acquired lock2");
                try {
                    Thread.sleep(100); // Delay to ensure deadlock
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread 2: Attempting to acquire lock1");
                synchronized(lock1) {
                    System.out.println("Thread 2: Acquired lock1");
                }
            }
        }
    
        public static void main(String[] args) {
            final DeadlockExample deadlock = new DeadlockExample();
            
            // Create and start first thread
            Thread thread1 = new Thread(() -> {
                deadlock.method1();
            });
            
            // Create and start second thread
            Thread thread2 = new Thread(() -> {
                deadlock.method2();
            });
            
            thread1.start();
            thread2.start();
        }
    }

    This program never ends: the two threads wait for each other forever, which would freeze your browser tab. Run it on your computer with java DeadlockExample.java.

    Java 21

Race Conditions

  • Race conditions occur when multiple threads access shared resources simultaneously

  • Prevention:

    1. Synchronization
    2. Atomic operations
    3. Thread-safe collections
  • Example:

    class UnsafeCounter {
      private int count = 0;
      
      // This method is not thread-safe
      void increment() {
          count++; // This is not an atomic operation
      }
    }

Thread Safety

Strategies of achieving thread safety:

  1. Synchronization

    class ThreadSafeCounter {
      private volatile int count = 0;
    
      synchronized void increment() {
        count++;
      }
    } 
  2. Using Atomic Classes

    import java.util.concurrent.atomic.AtomicInteger;
    
    class ThreadSafeCounter {
      private AtomicInteger count = new AtomicInteger(0);
    
      void increment() {
        count.incrementAndGet();
      }
    }
  3. Using Thread-Safe Collections

    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();