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.
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.
- 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
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
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!
How to avoid deadlocks:
Always lock resources in the same order
Use timeout-based locking like tryLock()
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;
}
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());
Use Cases:
Web servers
Background batch jobs
Scheduled tasks
** 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
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?
-
Automatic Memory Cleanup
You don’t have to manually track and free memory.
Reduces developer burden and errors.
- Avoids Memory Leaks
Unused objects will be cleaned, so memory doesn’t keep filling up.
Prevents crashes due to "OutOfMemoryError".
- Improves Performance
Frees memory for new objects, so your app runs smoothly.
- Safe and Consistent
GC avoids common bugs like dangling pointers or double free (common in C/C++).
Top comments (0)