下面的方法有 2 个 for 循环。firstloop 迭代 36000 次,inner forloop 迭代 24 次,所以插入记录的总数将是 864000 条。代码执行运行近 3.5 小时并终止。(记录插入失败) 仅进行 Session 关闭和事务提交在外部 for 循环结束之后。执行时发现RAM消耗近6.9GB
@SuppressWarnings("unchecked")
public void createBRResults() {
List<BusinessRules> businessRuleList = null;
Organization organization = null;
Brresults brresults = null;
Criteria criteria = null;
Criteria newCriteria = null;
String brStatus = "Live";
Date date = new Date();
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
if (callInfos == null) {
callInfos = getEntities(CallInfo.class);
}
for (CallInfo callInfo : callInfos) {
transaction = session.beginTransaction();
criteria = session.createCriteria(BusinessRules.class);
criteria.createCriteria("businessGoals").add(
Restrictions.eq("category", callInfo.getCategory()));
businessRuleList = criteria.list();
organization = callInfo.getOrganization();
for (BusinessRules businessRule : businessRuleList) {
brresults = new Brresults();
brresults.setBusinessRule(businessRule);
brresults.setCallInfo(callInfo);
brresults.setCreatedDate(date);
brresults.setModifiedDate(date);
brresults.setOrganization(organization);
brresults.setBrrStatus(brStatus);
brresults.setBrrValue(Math.random() < 0.5 ? 0 : 1);
session.save(brresults);
brresults = null;
}
criteria = null;
organization = null;
businessRuleList = null;
session.flush();
session.clear();
transaction.commit();
System.gc();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
session.close();
}
}
我附上了最后几行 GC 日志来指示内存分配
17034.595:[Full GC(人体工程学)[Psyounggen:979968K-> 979964K(1862144K)] 2.1041939 secs] [Times: user=8.61 sys=0.00, real=2.11 secs]
17036.699:[Full GC(人体工程学)[Psyounggen:979968K-> 979964K(1862144K)] 1.5930338 secs] [Times: user=9.39 sys=0.00, real=1.59 secs] 17038.292: [Full GC (Ergonomics) [PSYoungGen: 979968K->979964K(1862144K)] [ParOldGen: 5576158K->5676158K(565K1)] >6556122K(7438336K), [元空间: 23195K->23195K(1071104K)], 1.9376959 secs] [Times: user=8.51 sys=0.00, real=1.94 secs]
17040.230:[Full GC(人体工程学)[Psyounggen:979968K-> 830418K(1862144K)] 2.9929302 secs] [Times: user=17.97 sys=0.00, real=3.00 secs]
堆 PSYoungGen 总计 1862144K,已使用 889367K [0x0000000715d80000, 0x00000007bdc80000, 0x00000007c0000000)
eden space 979968K, 90% used [0x0000000715d80000,0x000000074c205e48,0x0000000751a80000) from space 882176K, 0% used [0x0000000787f00000,0x0000000787f00000,0x00000007bdc80000) to space 885760K, 0% used [0x0000000751a80000,0x0000000751a80000,0x0000000787b80000) ParOldGen total 5576192K, used 5576027K [0x00000005c1800000 , 0x0000000715d80000, 0x0000000715d80000) object space 5576192K, 99% used [0x00000005c1800000,0x0000000715d56d38,0x0000000715d80000) Metaspace used 23223K, capacity 23502K, committed 24064K, reserved 1071104K class space used 2443K, capacity 2537K, committed 2560K, reserved 1048576K
但是,如果我关闭会话并为每 24 次迭代再次打开,则记录插入成功,所需时间为 55 分钟。但 RAM 利用率约为 3GB。
为什么垃圾收集没有正常进行?代码中的错误是什么?