跳到主要内容

Programming Standards of Java Concurrency

· 阅读需 5 分钟

Thread safety is a critical aspect of building robust and scalable Java applications. Ensuring that your application handles concurrent operations correctly can prevent many common issues such as race conditions, deadlocks, and data inconsistencies. This article provides best practices and detailed guidelines for achieving thread safety in Java applications.


1. Thread Safety in Singleton Objects

  • Requirement: Ensure that singleton objects and their methods are thread-safe.
  • Explanation: Resource-driven classes, utility classes, and singleton factory classes must be thread-safe to prevent race conditions.

2. Meaningful Thread Naming

  • Requirement: Assign meaningful names to threads and thread pools for easier debugging.
  • Example: Custom thread factory with grouping based on external features (e.g., datacenter ID).
public class UserThreadFactory implements ThreadFactory {
private final String namePrefix;
private final AtomicInteger nextId = new AtomicInteger(1);

UserThreadFactory(String whatFeaturOfGroup) {
namePrefix = "From UserThreadFactory's " + whatFeaturOfGroup + "-Worker-";
}

@Override
public Thread newThread(Runnable task) {
String name = namePrefix + nextId.getAndIncrement();
Thread thread = new Thread(null, task, name, 0, false);
System.out.println(thread.getName());
return thread;
}
}

3. Thread Pool Usage

  • Requirement: Use thread pools instead of creating threads manually.
  • Explanation: Thread pools reduce the overhead of thread creation and destruction, preventing resource exhaustion and excessive context switching.

4. Explicit ThreadPoolExecutor Configuration

  • Requirement: Use ThreadPoolExecutor instead of Executors for creating thread pools.
  • Explanation: Executors can lead to resource exhaustion due to unbounded queues and thread creation.
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(queueCapacity),
new UserThreadFactory("Datacenter-1")
);

5. Thread-Safe Date Formatting

  • Requirement: Use thread-safe date formatting.
  • Example: Use ThreadLocal for SimpleDateFormat or switch to DateTimeFormatter in JDK 8.
private static final ThreadLocal<DateFormat> df = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

6. ThreadLocal Variable Cleanup

  • Requirement: Clean up ThreadLocal variables, especially in thread pools.
  • Example: Use try-finally blocks to ensure cleanup.
objectThreadLocal.set(userInfo);
try {
// ...
} finally {
objectThreadLocal.remove();
}

7. Locking Performance Considerations

  • Requirement: Minimize the performance impact of locks.
  • Explanation: Prefer lock-free data structures, lock only necessary code blocks, and use object-level locks instead of class-level locks.

8. Consistent Locking Order

  • Requirement: Maintain consistent locking order to prevent deadlocks.
  • Explanation: Ensure that all threads acquire locks in the same order to avoid circular wait conditions.

9. Exception Handling in Locking

  • Requirement: Handle exceptions properly to avoid lock leaks.
  • Example: Ensure that locks are released even if exceptions occur.
Lock lock = new ReentrantLock();
boolean isLocked = lock.tryLock();
if (isLocked) {
try {
doSomething();
doOthers();
} finally {
lock.unlock();
}
}

10. Optimistic and Pessimistic Locking

  • Requirement: Use appropriate locking strategies based on conflict probability.
  • Explanation: Use optimistic locking for low conflict scenarios and pessimistic locking for high conflict scenarios.

11. ScheduledExecutorService for Timed Tasks

  • Requirement: Use ScheduledExecutorService instead of Timer for concurrent timed tasks.
  • Explanation: Timer can terminate all tasks if one throws an uncaught exception.

12. CountDownLatch for Synchronization

  • Requirement: Use CountDownLatch for synchronization in multi-threaded tasks.
  • Explanation: Ensure that all threads call countDown and handle exceptions to avoid blocking the main thread.

13. Random Instance Management

  • Requirement: Avoid sharing Random instances across threads.
  • Example: Use ThreadLocalRandom in JDK 7+ or ensure each thread has its own Random instance.

14. Double-Checked Locking

  • Requirement: Use volatile for double-checked locking to avoid initialization issues.
  • Example: Declare the target variable as volatile.
private volatile Helper helper = null;

15. Volatile and Atomic Operations

  • Requirement: Use volatile for one-write-many-read scenarios and Atomic classes for multi-write scenarios.
  • Example: Use AtomicInteger or LongAdder for atomic operations.

16. HashMap Resize Risks

  • Requirement: Be cautious of HashMap resizing in high-concurrency scenarios.
  • Explanation: Resizing can lead to deadlocks and high CPU usage.

17. ThreadLocal Usage

  • Requirement: Use ThreadLocal with static variables carefully.
  • Explanation: ThreadLocal variables are shared within a thread but can cause issues if not managed properly.

By following these best practices, you can ensure that your Java application is thread-safe, scalable, and robust. These guidelines cover a wide range of scenarios, from basic thread safety to advanced concurrency patterns, helping you build high-performance applications.