Skip to content

bllexe/java-thread-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java Threading Kapsamlı Rehber

🚀 Giriş

Bu rehber Java'da threading konusunu OS Thread'lerden başlayarak Virtual Thread'lere kadar kapsamlı bir şekilde ele alır.

📚 İçindekiler

  1. OS Thread Temelleri
  2. Java Platform Threads
  3. Thread Synchronization
  4. Executor Framework
  5. Concurrent Collections
  6. Modern Threading (Java 8+)
  7. Virtual Threads (Java 21+)
  8. Best Practices Özeti

🔧 OS Thread Temelleri

Önemli Noktalar

  • Her OS thread ~1-2MB stack memory kullanır
  • Thread oluşturma maliyeti yüksektir (sistem call, memory allocation)
  • Context switching CPU overhead'i oluşturur
  • OS limitler nedeniyle binlerce thread'den fazla oluşturulamaz

Platform Thread Karakteristikleri

Memory: ~1-2MB per thread
Creation: Expensive (system calls)
Context Switch: CPU overhead
Limit: ~Few thousands
Management: OS level

Dikkat Edilecek Durumlar

  • ⚠️ Thread oluşturmayı minimize edin
  • ⚠️ Thread pool pattern'ini kullanın
  • ⚠️ Context switching maliyetini göz önünde bulundurun

🧵 Java Platform Threads

✅ YAPILMASI GEREKENLER

Thread Oluşturma

// ✅ İYİ - Runnable interface
Thread thread = new Thread(() -> {
    // task logic
});

// ❌ KÖTÜ - Thread extend etme
class MyThread extends Thread {
    // Inheritance waste
}

ExecutorService Kullanımı

// ✅ İYİ - Thread pool
ExecutorService executor = Executors.newFixedThreadPool(4);

// ❌ KÖTÜ - Manuel thread oluşturma
for (int i = 0; i < 100; i++) {
    new Thread(task).start(); // Resource waste
}

Temel Kurallar

  1. Thread extend etmek yerine Runnable implement edin
  2. Lambda expressions kullanın (modern ve temiz)
  3. join() ile thread'lerin bitmesini bekleyin
  4. Daemon thread'leri background işler için kullanın
  5. Thread priority'ye güvenmeyin (OS dependent)

🔒 Thread Synchronization

Race Condition'dan Kaçınma

AtomicInteger Kullanımı

// ✅ İYİ - Thread-safe
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();

// ❌ KÖTÜ - Race condition
int counter = 0;
counter++; // Not thread-safe

Synchronized vs ReentrantLock

// ✅ İYİ - ReentrantLock (özellikle Virtual Threads ile)
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}

// ⚠️ DIKKAT - Synchronized (Virtual Thread pinning yapabilir)
synchronized(this) {
    // critical section - can pin virtual threads
}

Synchronization Best Practices

  1. AtomicInteger, AtomicBoolean gibi atomic classes tercih edin
  2. ConcurrentHashMap kullanın, synchronized Map yerine
  3. ReentrantLock kullanın, synchronized yerine (özellikle Virtual Threads)
  4. Lock timeout kullanın (tryLock with timeout)
  5. Nested synchronized blocks'tan kaçının
  6. Synchronized block'ları küçük tutun
  7. Lock sırasını tutarlı tutun (deadlock prevention)

Deadlock Prevention

// ✅ İYİ - Consistent lock ordering
private final Object lock1 = new Object();
private final Object lock2 = new Object();

// Always acquire locks in same order
synchronized(lock1) {
    synchronized(lock2) {
        // safe
    }
}

🏊‍♂️ Executor Framework

Thread Pool Seçimi

CPU-bound Tasks

// ✅ CPU-bound için
ExecutorService cpuExecutor = Executors.newFixedThreadPool(
    Runtime.getRuntime().availableProcessors()
);

I/O-bound Tasks

// ✅ I/O-bound için
ExecutorService ioExecutor = Executors.newCachedThreadPool();
// veya
ExecutorService ioExecutor = Executors.newFixedThreadPool(50);

Executor Best Practices

  1. newFixedThreadPool CPU-bound task'lar için
  2. newCachedThreadPool I/O-bound task'lar için
  3. CompletableFuture async chain'ler için
  4. Always shutdown executors properly (try-with-resources)
  5. Handle RejectedExecutionException
  6. Custom ThreadFactory kullanın naming için

Graceful Shutdown

executor.shutdown();
try {
    if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        executor.shutdownNow();
    }
} catch (InterruptedException e) {
    executor.shutdownNow();
    Thread.currentThread().interrupt();
}

📦 Concurrent Collections

Collection Seçimi

// ✅ İYİ
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
BlockingQueue<String> queue = new LinkedBlockingQueue<>();

// ❌ KÖTÜ
Map<String, Integer> map = Collections.synchronizedMap(new HashMap<>());

Synchronization Utilities

Semaphore - Resource Limiting

Semaphore connectionPool = new Semaphore(3); // Max 3 connections
connectionPool.acquire();
try {
    // use resource
} finally {
    connectionPool.release();
}

CountDownLatch - One-time Coordination

CountDownLatch latch = new CountDownLatch(3);
// Workers countdown when done
latch.await(); // Main waits for all

Concurrent Collections Best Practices

  1. ConcurrentHashMap > synchronized Map
  2. BlockingQueue producer-consumer için
  3. Semaphore resource limiting için
  4. ReadWriteLock read-heavy scenarios için
  5. Lock'ları finally block'ta unlock edin

🚄 Modern Threading (Java 8+)

Parallel Streams

Ne Zaman Kullanılır

// ✅ İYİ - Large dataset + CPU-bound
List<Integer> largeList = IntStream.rangeClosed(1, 1_000_000).boxed().toList();
long sum = largeList.parallelStream()
                   .mapToLong(i -> heavyComputation(i))
                   .sum();

// ❌ KÖTÜ - Small dataset
List<Integer> smallList = Arrays.asList(1, 2, 3, 4, 5);
smallList.parallelStream() // Overhead > benefit
         .mapToInt(i -> i * i)
         .sum();

Parallel Stream Best Practices

  1. Large dataset'ler için kullanın (>1000 elements)
  2. CPU-bound operations için ideal
  3. ArrayList > LinkedList (spliterator efficiency)
  4. Custom ForkJoinPool I/O operations için
  5. Thread-safe operations kullanın

CompletableFuture Best Practices

  1. I/O operations için async chains
  2. Exception handling ile exceptionally()
  3. Multiple futures için thenCombine()
  4. Custom executor kullanın task type'a göre
  5. Timeout ekleyin get(timeout)

🌟 Virtual Threads (Java 21+)

Virtual Thread Avantajları

  • Milyonlarca thread daha az memory ile
  • JVM-managed (carrier thread'ler üzerinde)
  • Perfect I/O-bound operations için
  • Platform thread'lerin 1000x daha az memory

Virtual Thread Creation

// ✅ İYİ - Virtual thread creation
Thread virtualThread = Thread.ofVirtual().start(() -> {
    // I/O-bound task
});

// ✅ İYİ - Virtual thread executor
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
    // Submit I/O tasks
}

// ✅ İYİ - Thread factory
ThreadFactory factory = Thread.ofVirtual().factory();

Virtual Thread Pinning - KRİTİK!

KAÇINILMASI GEREKENLER

// ❌ KÖTÜ - Pinning causes (synchronized)
synchronized(lock) {
    Thread.sleep(1000); // Pins virtual thread to carrier
}

// ❌ KÖTÜ - JNI calls
nativeMethod(); // Can cause pinning

YAPILMASI GEREKENLER

// ✅ İYİ - ReentrantLock (no pinning)
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
    Thread.sleep(1000); // Virtual thread can be unmounted
} finally {
    lock.unlock();
}

Virtual Thread Best Practices

✅ YAPIN

  1. I/O-bound tasks için kullanın (HTTP calls, DB operations)
  2. Executors.newVirtualThreadPerTaskExecutor() kullanın
  3. ReentrantLock kullanın, synchronized yerine
  4. try-with-resources executor management için
  5. Structured concurrency pattern'ini uygulayın

❌ YAPMAYIN

  1. CPU-intensive tasks için kullanmayın
  2. synchronized blocks kullanmayın (pinning risk)
  3. Virtual thread'leri pool etmeyin
  4. Excessive ThreadLocal kullanmayın (memory risk)
  5. JNI calls'tan kaçının

Memory Comparison

Platform Thread: ~1-2MB per thread
Virtual Thread:  ~Few KB per thread
Scalability:     Thousands vs Millions
Management:      OS vs JVM

🎯 Use Case Rehberi

Platform Threads Kullanın

  • ✅ CPU-bound computations
  • ✅ Long-running background services
  • ✅ Limited concurrency scenarios
  • ✅ Legacy system integrations

Virtual Threads Kullanın (Java 21+)

  • ✅ HTTP client calls
  • ✅ Database operations
  • ✅ File I/O operations
  • ✅ Web servers (request per thread)
  • ✅ Microservice communications

Thread Pool Kullanın

  • ✅ Bounded resource scenarios
  • ✅ CPU-intensive parallel processing
  • ✅ Task batching requirements
  • ✅ Complex lifecycle management

⚠️ Critical Best Practices Özeti

Thread Safety

  1. AtomicInteger > int++ (race conditions)
  2. ConcurrentHashMap > synchronized HashMap
  3. Immutable objects tercih edin
  4. Defensive copying yapın

Resource Management

  1. Always shutdown executors
  2. Use try-with-resources
  3. Handle InterruptedException properly
  4. Avoid resource leaks

Virtual Thread Specifics

  1. ReentrantLock > synchronized
  2. Avoid pinning operations
  3. Don't pool virtual threads
  4. Minimize ThreadLocal usage

Performance

  1. Right tool for right job
  2. Measure before optimizing
  3. Consider data locality
  4. Profile thread usage

Debugging

  1. Use meaningful thread names
  2. Log thread information
  3. Monitor thread pools
  4. Use JVM monitoring tools

🔧 Quick Reference

Thread Creation Priority

1. Virtual Threads (Java 21+) - for I/O-bound
2. CompletableFuture - for async chains  
3. ExecutorService - for managed concurrency
4. Direct Thread - only for simple cases

Synchronization Priority

1. Concurrent Collections (ConcurrentHashMap)
2. Atomic Classes (AtomicInteger)
3. ReentrantLock (especially with Virtual Threads)
4. synchronized (last resort, avoid with Virtual Threads)

Common Mistakes

❌ Creating threads manually instead of using executors
❌ Using synchronized with Virtual Threads
❌ Not handling InterruptedException
❌ Forgetting to shutdown executors
❌ Using parallel streams for small datasets
❌ Race conditions with shared mutable state
❌ Deadlocks with inconsistent lock ordering
❌ ThreadLocal abuse with Virtual Threads

📖 Sonuç

Java threading evrimi:

  • Java 1.0: Basic threads
  • Java 5: Executor Framework
  • Java 8: Parallel Streams, CompletableFuture
  • Java 21: Virtual Threads (Project Loom)

Modern Java'da threading yaklaşımı:

  1. Virtual Threads I/O-bound tasks için
  2. Platform Threads + Executors CPU-bound tasks için
  3. Concurrent Collections thread-safe data structures için
  4. CompletableFuture async programming için

About

Examples related to Java threads and java-21 virtual threads

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages