DEV Community

Codes With Pankaj
Codes With Pankaj

Posted on

Java Threads: Tips and Tricks with Examples

Examples:

  1. Thread Creation:
    • Use Runnable interface for thread creation to promote better design.
   class MyRunnable implements Runnable {
       public void run() {
           // Your thread logic here
       }
   }

   Thread myThread = new Thread(new MyRunnable());
   myThread.start();
Enter fullscreen mode Exit fullscreen mode
  1. Thread Safety:
    • Synchronize critical sections to avoid data inconsistency.
   class Counter {
       private int count = 0;

       public synchronized void increment() {
           count++;
       }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Thread Join:
    • Use join() to wait for a thread to finish its execution.
   Thread t1 = new Thread(() -> {
       // Your thread logic
   });

   t1.start();
   t1.join(); // Main thread waits for t1 to finish
Enter fullscreen mode Exit fullscreen mode
  1. Thread Pools:
    • Utilize ExecutorService for managing thread pools.
   ExecutorService executor = Executors.newFixedThreadPool(5);

   for (int i = 0; i < 10; i++) {
       executor.execute(new MyRunnable());
   }

   executor.shutdown();
Enter fullscreen mode Exit fullscreen mode
  1. Atomic Operations:
    • Use Atomic classes for atomic operations to avoid race conditions.
   AtomicInteger atomicInt = new AtomicInteger(0);

   atomicInt.incrementAndGet();
Enter fullscreen mode Exit fullscreen mode
  1. Thread Interruption:
    • Gracefully handle thread interruption.
   while (!Thread.interrupted()) {
       // Your thread logic
   }
Enter fullscreen mode Exit fullscreen mode
  1. Thread Local:
    • Utilize ThreadLocal for thread-specific data.
   ThreadLocal<SimpleDateFormat> dateFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

   String formattedDate = dateFormat.get().format(new Date());
Enter fullscreen mode Exit fullscreen mode
  1. Thread Priority:
    • Use thread priority cautiously, as it may not be honored on all platforms.
   myThread.setPriority(Thread.MAX_PRIORITY);
Enter fullscreen mode Exit fullscreen mode
  1. Volatile Keyword:
    • Use volatile keyword for variables accessed by multiple threads to ensure visibility.
   private volatile boolean flag = false;
Enter fullscreen mode Exit fullscreen mode
  1. ExecutorService Shutdown:

    • Gracefully shut down the ExecutorService.
    executor.shutdown();
    try {
        if (!executor.awaitTermination(500, TimeUnit.MILLISECONDS)) {
            executor.shutdownNow();
        }
    } catch (InterruptedException e) {
        executor.shutdownNow();
        Thread.currentThread().interrupt();
    }
    

Remember to handle exceptions, and always be mindful of potential deadlock situations when working with threads in Java.

Read more Visit git repository

https://github.com/Pankaj-Str/Learn-JAVA-SE/tree/main/Day_59_Threading

Top comments (1)

Collapse
 
siy profile image
Sergiy Yevtushenko
  • It's better to avoid manual thread creation for regular threads.
  • The synchronized blocks are not friendly to virtual threads, so it's better to avoid them and use locks (ReadWriteLock, ReentrantLock, etc. deepending on the task).
  • ThreadLocal is prone to memory leaks and does not work properly with virtual threads. Instead, it's better to use scoped variables (preview feature in Java 21).