线程池——JAVA并发编程指南

来源:互联网 发布:澳洲硕士知乎 编辑:程序博客网 时间:2024/05/23 05:07

TPS00-J. 用线程池实现应用在流量暴涨时优雅降级

TPS01-J. 不要再有界线程池中运行互相依赖的任务

有界线程池是指其同一时刻执行任务的线程总数有上限。需要等待其他任务完成的任务不应该放到游街线程池中执行

有一种死锁叫做线程饿死,当线程池中的所有线程都在等待一个尚未开始的任务(只是进入了线程池的内部队列),这种死锁就会发生了

这种问题很有欺骗性,因为当需要的线程较少的时候程序可以正常的运行。有时候调大线程数就可以缓解这个问题。但是,确定合适的数量通常很难

错误代码示例

public final class ValidationService {private final ExecutorService pool;public ValidationService(int poolSize) {pool = Executors.newFixedThreadPool(poolSize);}public void shutdown() {pool.shutdown();}public StringBuilder fieldAggregator(String... inputs)throws InterruptedException, ExecutionException {StringBuilder sb = new StringBuilder();Future<String>[] results = new Future[inputs.length]; // Stores the resultsfor (int i = 0; i < inputs.length; i++) { // Submits the tasks to thread poolresults[i] = pool.submit(new ValidateInput<String>(inputs[i], pool));}for (int i = 0; i < inputs.length; i++) { // Aggregates the resultssb.append(results[i].get());}return sb;}}public final class ValidateInput<V> implements Callable<V> {private final V input;private final ExecutorService pool;ValidateInput(V input, ExecutorService pool) {this.input = input;this.pool = pool;}@Override public V call() throws Exception {// If validation fails, throw an exception hereFuture<V> future = pool.submit(new SanitizeInput<V>(input)); // Subtaskreturn (V)future.get();}}public final class SanitizeInput<V> implements Callable<V> {private final V input;SanitizeInput(V input) {this.input = input;}@Override public V call() throws Exception {// Sanitize input and returnreturn (V)input;}}



TPS02-J. 确保提交给一个线程池的任务是可中断的

TPS03-J. 确保线程池中的任务不会默默的失败

TPS04-J. 使用线程池时要确保ThreadLocal被重置


0 0
原创粉丝点击