DEV Community

Cover image for June Ponal July Katre ! - The JVM MeetUp
s mathavi
s mathavi

Posted on

June Ponal July Katre ! - The JVM MeetUp

I want to share my thoughts about Multithreading and Garbage Collection… what i learned in jvm meetup

What is Multi Threading?

Multi Threading means running multiple threads within a single process simultaneously. It helps in using the CPU efficiently and allows multitasking.

 Thread = A small unit of execution inside a program.
All threads in a process share the same memory.
Enter fullscreen mode Exit fullscreen mode

Example:

In a mobile app,

  • One thread refreshes the UI
  • Another thread fetches data in the background
  • Another handles file downloads

If these run at the same time, the app will be smooth and responsive.

  1. Main Thread vs Daemon Thread

** Main Thread:**

  • The default thread that starts when a program runs
  • The program waits until this thread finishes

Example:
In Java, public static void main() runs in the main thread.

** Daemon Thread:**

Background thread that supports main tasks

It automatically stops when the main thread ends
Enter fullscreen mode Exit fullscreen mode

Example:
Garbage Collector, Background log writers.

Race Condition

A race condition happens when two or more threads access and modify shared data at the same time, leading to unpredictable results.

Example:
In a banking app:

Thread 1: balance = balance + 100

Thread 2: balance = balance + 200
Enter fullscreen mode Exit fullscreen mode

Without synchronization, the final balance might be incorrect (e.g., 100 instead of 300).

Solution: Use synchronized or locks to control access.

  • Deadlock

A deadlock occurs when two or more threads wait for each other to release resources, and nothing proceeds — the program freezes.

Example:

Thread 1 holds Lock A and waits for Lock B

Thread 2 holds Lock B and waits for Lock A
Neither can proceed → Deadlock!
Enter fullscreen mode Exit fullscreen mode

How to avoid deadlocks:

Always lock resources in the same order

Use timeout-based locking like tryLock()
Enter fullscreen mode Exit fullscreen mode

Thread Synchronization

Synchronization ensures that only one thread can access a shared resource at a time, avoiding conflicts or data corruption.

Example in Java:

synchronized void deposit(int amount) {
   balance = balance + amount;
}
Enter fullscreen mode Exit fullscreen mode

Other threads must wait until this thread completes the method.

** Thread Pool**

Instead of creating new threads again and again, a thread pool maintains a pool of pre-created threads which are reused. It improves performance.

Example in Java:

ExecutorService pool = Executors.newFixedThreadPool(5);
pool.execute(new MyTask());
Enter fullscreen mode Exit fullscreen mode

Use Cases:

Web servers

Background batch jobs

Scheduled tasks
Enter fullscreen mode Exit fullscreen mode

** Atomic Variables**

Atomic classes allow thread-safe operations without locking. They use low-level CPU instructions to avoid race conditions.

Example in Java:

AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet(); // Thread-safe
Enter fullscreen mode Exit fullscreen mode

Use Case:

  • Counting
  • Generating unique IDs
  • Tracking metrics

Semaphore

A semaphore is a mechanism to limit how many threads can access a shared resource at the same time.

Example:
If a parking lot has 5 spots, the 6th car must wait. That’s how a semaphore works.

Semaphore sem = new Semaphore(3); // Only 3 threads allowed
sem.acquire();
sem.release();

Use Cases:

  • Limiting API requests
  • Database connection pools

What is Garbage Collection (GC)?

Garbage Collection (GC) is an automatic memory management process.
It frees up memory that is no longer being used by the program.

In Simple Words:
When you create objects in Java or any high-level language, they use memory (RAM). If an object is no longer needed, the garbage collector finds it and removes it — so the memory can be reused.

You don’t need to delete objects manually. GC does it for you!

Why is Garbage Collection important?

  1. Automatic Memory Cleanup

    You don’t have to manually track and free memory.

    Reduces developer burden and errors.

    1. Avoids Memory Leaks

    Unused objects will be cleaned, so memory doesn’t keep filling up.

    Prevents crashes due to "OutOfMemoryError".

    1. Improves Performance

    Frees memory for new objects, so your app runs smoothly.

    1. Safe and Consistent

    GC avoids common bugs like dangling pointers or double free (common in C/C++).

Top comments (0)