Java Multithreading | Part 1

Published on July 15, 2024 4 min read

Tags:
Java

Understanding Processes and Threads in Java

Process

A process is an instance of a program that is being executed.

It has its own resources like memory and threads, which the operating system allocates when the process is created.

Compilation: Running javac Test.java generates bytecode that can be executed by the JVM.
Execution: Using java Test.class starts a new process where Test is the class with the public static void main(String[] args) method.

Thread

A thread is the smallest sequence of instructions executed independently by the CPU.

A process can have multiple threads. When a process is created, it starts with one main thread, from which multiple threads can be created to perform tasks concurrently.

Example:

public class Main {
    public static void main(String[] args) {
        System.out.println("Inside main method, thread - " + Thread.currentThread().getName());
    }
}
//output - Inside main method, thread - main

Memory Segments in JVM

Multitasking vs. Multithreading

Code Segment

  • Contains the compiled bytecode of the Java program.
  • Read-only.
  • Shared by all threads within the same process.

Data Segment

  • Contains global and static variables.
  • Shared by all threads within the same process.
  • Requires synchronization for thread safety.

Heap

  • Allocated for objects created at runtime using the new keyword.
  • Shared among all threads of the same process (but not within Processes).
  • Requires synchronization for thread safety.

Stack

  • Each thread has its own stack.
  • Manages method calls and local variables.

Register

  • Used by the JIT compiler to optimize generated machine code.
  • Each thread has its own register, aiding in context switching.

Program Counter

  • Also known as the program counter, it points to the currently executing instruction.
  • Increments after the successful execution of an instruction.

Memory Allocation for Process: When creating a process with java MainClassName, a new JVM instance is created. We can specify the heap memory allocation using:

  • -Xms<size>: Sets the initial heap size. Example: -Xms256m allocates 256MB initially.
  • -Xmx<size>: Sets the maximum heap size. Example: -Xmx2g allocates a maximum of 2GB. Exceeding this limit results in an OutOfMemoryError.
java -Xms256m -Xmx2g MainClassName

Multithreading in Java

Definition: Allows a program to perform multiple tasks simultaneously. Multiple threads share the same resources but can perform tasks independently.

Benefits:

  • Improved performance through task parallelism.
  • Increased responsiveness.
  • Efficient resource sharing.

Challenges:

  • Concurrency issues like deadlock and data inconsistency.
  • Overhead of synchronization.
  • Difficulty in testing and debugging.

Multitasking vs. Multithreading

Multitasking involves running multiple processes, while multithreading involves running multiple threads within a single process, allowing more efficient use of resources.

AspectMultitaskingMultithreading
DefinitionRunning multiple processes concurrently.Running multiple threads within a single process.
Memory SpaceEach process has its own memory space.Threads share the same memory space within a process.
Resource SharingProcesses do not share resources directly.Threads share resources like memory and files.
Creation OverheadHigher overhead due to the creation of separate memory space and resources for each process.Lower overhead, as threads share the same memory and resources.
CommunicationRequires Inter-Process Communication (IPC) mechanisms like pipes and message queues.Direct communication via shared memory, requiring synchronization.
ConcurrencyOS handles scheduling and execution, switching between processes.Managed within the process, allowing finer control over execution.
ExampleRunning multiple applications like a web browser, text editor, and media player simultaneously.A Java application with multiple threads handling different tasks (e.g., user input, background tasks).