Java 代码: package com.zhuanzhuan.financemall.utils.parallel; import…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
package com.zhuanzhuan.finance_mall.utils.parallel;
import com.zhuanzhuan.finance_mall.utils.parallel.dto.TaskGraph; import com.zhuanzhuan.finance_mall.utils.parallel.dto.TaskNode; import lombok.extern.slf4j.Slf4j;
import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;
/**
通用任务执行入口
@Author youzhiqiang
@Date 2025-05-29 10:26 */ @Slf4j public class ParallelTaskEngine {
private final ExecutorService executor; private final TaskGraph taskGraph;
public ParallelTaskEngine(ExecutorService executor, TaskGraph taskGraph) { this.executor = executor; this.taskGraph = taskGraph; }
public void execute(T context, long timeoutMillis) throws Exception { // 存储所有任务的执行Future,用于后续等待任务完成 Map<String, Future> futures = new ConcurrentHashMap<>(); // 存储每个任务的计数器,用于同步任务的依赖完成情况 Map<String, CountDownLatch> latchMap = new ConcurrentHashMap<>(); // 存储任务开始时间 Map<String, Long> taskStartTimes = new ConcurrentHashMap<>();
// 初始化每个任务的计数器
taskGraph.getDependencyCounts().forEach((name, count) ->
latchMap.put(name, new CountDownLatch(count)));
// 遍历所有任务,提交任务到线程池执行
for (String taskName : taskGraph.getTaskMap().keySet()) {
futures.put(taskName, executor.submit(() -> {
TaskNode<T> node = taskGraph.getTaskMap().get(taskName);
CountDownLatch latch = latchMap.get(taskName);
try {
doRunTaskLogics(context, taskName, latch, node, taskStartTimes);
} finally {
// 通知依赖此任务的其他任务
taskGraph.getReverseDeps().getOrDefault(taskName, Collections.emptyList())
.forEach(dep -> latchMap.get(dep).countDown());
}
return null;
}));
}
// 等待所有任务完成或超时
try {
for (Future<Void> future : futures.values()) {
future.get(timeoutMillis, TimeUnit.MILLISECONDS);
}
} catch (TimeoutException e) {
// 取消所有未完成的任务
futures.values().forEach(future -> future.cancel(true));
throw e;
}
}
private static void doRunTaskLogics(T context, String taskName, CountDownLatch latch, TaskNode node, Map<String, Long> taskStartTimes) throws TimeoutException, InterruptedException { // 记录等待依赖任务的时间 long waitStartTime = System.currentTimeMillis(); try { boolean awaitResult = latch.await(node.waitTimeoutMillis, TimeUnit.MILLISECONDS); if (!awaitResult) { throw new TimeoutException("Task " + taskName + " timed out waiting for dependencies"); } } catch (InterruptedException e) { log.error("ParallelTaskEngine taskName={} interrupted while waiting for dependencies", taskName, e); Thread.currentThread().interrupt(); throw e; } long waitTime = System.currentTimeMillis() - waitStartTime;
// 记录任务开始时间
taskStartTimes.put(taskName, System.currentTimeMillis());
// 先执行主任务逻辑
try {
log.info("ParallelTaskEngine taskName={} begin.", taskName);
node.logic.run(context);
} catch (Exception e) {
log.error("ParallelTaskEngine taskName={} error. {}", taskName, node.fallback != null ? "has fallback" : "", e);
// 如果存在降级方法,尝试执行降级逻辑
if (node.fallback != null) {
try {
node.fallback.accept(context);
} catch (Exception fallbackError) {
log.error("ParallelTaskEngine taskName={} fallback Task run failed!", taskName, fallbackError);
throw e;
}
} else {
throw e;
}
}
// 计算任务执行时间
long taskEndTime = System.currentTimeMillis();
long taskStartTime = taskStartTimes.get(taskName);
long taskExecutionTime = taskEndTime - taskStartTime;
// 记录任务执行耗时
log.info("ParallelTaskEngine taskName={} completed. waitTime={}ms, executionTime={}ms, totalTime={}ms",
taskName, waitTime, taskExecutionTime, waitTime + taskExecutionTime);
} }
指出以上Java代码存在哪些问题?若在工程中使用有哪些可以优化的空间?(使用中文回答)
我来分析这段并行任务执行引擎的代码,指出存在的问题和优化空间:
建议的优化方案:
public class ParallelTaskEngine<T> {
// 添加任务执行状态枚举
public enum TaskStatus {
PENDING, RUNNING, COMPLETED, FAILED, CANCELLED
}
// 添加任务执行上下文
private class TaskContext {
private final Map<String, TaskStatus> statusMap = new ConcurrentHashMap<>();
private final Map<String, Long> startTimes = new ConcurrentHashMap<>();
private final Map<String, Throwable> errors = new ConcurrentHashMap<>();
}
// 添加监控指标收集
private final MetricsCollector metricsCollector;
// 添加重试策略
private final RetryStrategy retryStrategy;
// 提供构建器
public static class Builder<T> {
// 构建器实现
}
// 提供更细粒度的执行控制
public void executeWithCallback(T context, long timeoutMillis,
ProgressCallback callback) throws ParallelTaskException {
// 实现
}
// 提供暂停/恢复功能
public void pause() {
// 实现
}
public void resume() {
// 实现
}
// 提供优雅关闭
public void shutdown(long timeout) {
// 实现
}
}
这些优化建议可以根据实际业务场景和性能需求选择性实施。关键是要在可用性、可维护性和性能之间找到平衡点。