【发布时间】:2015-11-23 09:54:18
【问题描述】:
我正在开发基于 Spring+Hibernate 的 Web 应用程序。 在这个应用程序中,我必须对数据库中可用的 50000 条记录进行计算。 当前逻辑:-
- 循环 0 到 50000(所有 50000 条记录相互独立)
- 选择第 i 个元素
- 对第 i 个元素进行计算(如果存在则删除 CALCULATION_TEMP 表,创建新表 CALCULATION_TEMP 并在 CALCULATION_TEMP 表中插入计算)
- 对第 3 步表做一些计算并得到结果
- 将第 4 步的结果放入 Results 表中
目前,单线程完成所有这些计算大约需要 38 小时。
现在我们想通过多线程运行这个系统。 出于测试目的,我记录了 50 条记录。
使用单线程大约需要 30 秒。
使用两个线程:-
- 一半记录由第一个线程执行,其余记录由第二个线程执行。
- 现在我为两个线程使用了两个 TEMP 表。 (TEMP1 和 TEMP2)
- 需要 225 秒。
粗略代码:-
for (int i = 0; i < recordsSize; i++) {
final int j = i;
String recordId = list.get(i);
// Method call : Code for creating CALCULATION_TEMP table
// CALCULATION_TEMP table will contain dynamic number of column. It is depends on the record data (50 to 70 columns)
// return flag value
boolean flag = xyzMethod(....);
if (flag) {
// All calculation done in this method
// Around 600 - 700 rows will be created into CALCULATION_TEMP table on the basis of calculation logic
Object fileMapColumnData[] = /* Method call */;
// Insert result for one record into RESULT table for unique recordId (this result is calculated in CALCULATION_TEMP table)
insertIntoResultTable(....);
// Drop CALCULATION_TEMP table
} else {
LOGGER.error("Unable to calculate ... because of some wrong data");
loggerDTO.getCustomLogger().severe("Unable to calculate ... because of some wrong data");
}
if (i % 100 == 0) {
calculationDao.flushAndClear();
}
// Thread for showing process completion status in percentage
Thread t = new Thread() {
@Override
public void run() {
getPercentageDone((float) recordsSize, (float) (j + 1));
}
};
t.start();
}
请提出建议,如何提高性能。
【问题讨论】:
-
你不能用不同的键使用同一个临时表吗?另外,您确定不能通过 DB 中的简单过程来实现此计算吗?
-
正如@aksappy 提到的,它更像是数据库方面的工作,而不是 Java 方面..
-
一个临时表引用一个结果。所以我们不能使用相同的临时表。根据客户要求,我们不能使用存储过程,
-
我不知道你的计算。使用 SQL GROUP 或 COUNT 函数计算元素怎么样?
-
计算非常复杂。我每个月都需要计算。就像一条记录,我有 20 年的数据。因此,将创建 20*12 = 240 行,每条记录具有动态列数(大约 50 到 70)。这就是为什么我需要为每条记录重新创建表。
标签: java multithreading spring hibernate transactions