Programming Standards of Java Concurrency
· 阅读需 5 分钟
- 1. Thread Safety in Singleton Objects
- 2. Meaningful Thread Naming
- 3. Thread Pool Usage
- 4. Explicit ThreadPoolExecutor Configuration
- 5. Thread-Safe Date Formatting
- 6. ThreadLocal Variable Cleanup
- 7. Locking Performance Considerations
- 8. Consistent Locking Order
- 9. Exception Handling in Locking
- 10. Optimistic and Pessimistic Locking
- 11. ScheduledExecutorService for Timed Tasks
- 12. CountDownLatch for Synchronization
- 13. Random Instance Management
- 14. Double-Checked Locking
- 15. Volatile and Atomic Operations
- 16. HashMap Resize Risks
- 17. ThreadLocal Usage
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
ThreadPoolExecutorinstead ofExecutorsfor creating thread pools. - Explanation:
Executorscan 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
ThreadLocalforSimpleDateFormator switch toDateTimeFormatterin JDK 8.
private static final ThreadLocal<DateFormat> df = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
6. ThreadLocal Variable Cleanup
- Requirement: Clean up
ThreadLocalvariables, especially in thread pools. - Example: Use
try-finallyblocks 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
ScheduledExecutorServiceinstead ofTimerfor concurrent timed tasks. - Explanation:
Timercan terminate all tasks if one throws an uncaught exception.
12. CountDownLatch for Synchronization
- Requirement: Use
CountDownLatchfor synchronization in multi-threaded tasks. - Explanation: Ensure that all threads call
countDownand handle exceptions to avoid blocking the main thread.
13. Random Instance Management
- Requirement: Avoid sharing
Randominstances across threads. - Example: Use
ThreadLocalRandomin JDK 7+ or ensure each thread has its ownRandominstance.
14. Double-Checked Locking
- Requirement: Use
volatilefor 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
volatilefor one-write-many-read scenarios andAtomicclasses for multi-write scenarios. - Example: Use
AtomicIntegerorLongAdderfor atomic operations.
16. HashMap Resize Risks
- Requirement: Be cautious of
HashMapresizing in high-concurrency scenarios. - Explanation: Resizing can lead to deadlocks and high CPU usage.
17. ThreadLocal Usage
- Requirement: Use
ThreadLocalwith static variables carefully. - Explanation:
ThreadLocalvariables 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.