Concurrency and Threads in Java

Concurrency

  • Two or more threads executing simultaneously.
  • Implemented as separate processes or threads (threads preferred for shared memory).

Uses of Concurrency

  • Background tasks (formatting, printing).
  • Responsive UI during long tasks.
  • Parallel processing.

Thread Creation in Java

  • Extend Thread class and override run().
  • Implement Runnable interface.
  • Use lambda expressions.

Thread Basics

  • sleep(duration): pauses thread execution.
  • interrupt(): sends interruption signal, sets interrupt flag. Can throw InterruptedException if thread is sleeping or blocked.
  • join(): waits for a thread to complete.

Collaboration

  • Threads need to collaborate when sharing data.
  • Simplest form: one thread waits for another to complete using t0.join().

Interference

  • Race conditions occur when instruction order matters, leading to issues like lost updates.
  • Incrementing a counter (c++) is not atomic: read, increment register, write back.

Synchronized Keyword

  • Defines a block of code that only one thread can enter at a time.
  • Uses a locking object; multiple blocks with the same lock ensure only one thread executes any of them.
  • Can be used as a method modifier for synchronizing entire methods.

Memory Consistency

  • Ensures threads see consistent data, separate from race conditions.
  • synchronized fixes memory consistency by ensuring CPU cache is consistent with main memory.

Volatile Keyword

  • Guarantees atomicity (relevant for double and long on 32-bit architectures).
  • Ensures reads/writes are immediately copied to/from main memory, guaranteeing memory consistency.

Synchronized vs. Volatile

  • synchronized: fixes race conditions and memory consistency for code blocks.
  • volatile: fixes memory consistency for individual variables; more efficient, doesn't block.

Deadlock

  • Occurs when threads wait for each other indefinitely.
  • Bad use of synchronized can trigger deadlock.
  • Elimination: ensure consistent lock acquisition order or use a third lock.

Concurrent Programming

  • Difficult and prone to errors; Java offers classes and libraries to help.
  • GUI libraries use event dispatch queues to minimize synchronization needs.