Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Set<Bucket> expiredBuckets = new HashSet<Bucket>();
final int batchSize = 100;
ExecutorAllCompletionService eacs = new ExecutorAllCompletionService(threadPool);
Set<Bucket> emptyBuckets = new HashSet<Bucket>(batchSize);
int taskCount = 0;
try {
try {
String sql = tableManipulation.getSelectExpiredRowsSql();
conn = connectionFactory.getConnection();
ps = conn.prepareStatement(sql);
ps.setLong(1, ctx.getTimeService().wallClockTime());
rs = ps.executeQuery();
while (rs.next()) {
Integer bucketId = rs.getInt(2);
if (immediateLockForWriting(bucketId)) {
if (log.isTraceEnabled()) {
log.tracef("Adding bucket keyed %s for purging.", bucketId);
}
Bucket bucket;
InputStream binaryStream = rs.getBinaryStream(1);
bucket = unmarshallBucket(binaryStream);
bucket.setBucketId(bucketId);
expiredBuckets.add(bucket);
if (expiredBuckets.size() == batchSize) {
eacs.submit(new BucketPurger(expiredBuckets, task, ctx.getMarshaller(), conn, emptyBuckets));
taskCount++;
expiredBuckets = new HashSet<Bucket>(batchSize);
}
} else {
if (log.isTraceEnabled()) {
log.tracef("Could not acquire write lock for %s, this won't be purged even though it has expired elements", bucketId);
}
}
}
if (!expiredBuckets.isEmpty())
eacs.submit(new BucketPurger(expiredBuckets, task, ctx.getMarshaller(), conn, emptyBuckets));
} catch (Exception ex) {
// if something happens make sure buckets locks are being release
releaseLocks(expiredBuckets);
log.failedClearingJdbcCacheStore(ex);
throw new PersistenceException("Failed clearing JdbcBinaryStore", ex);
} finally {
JdbcUtil.safeClose(ps);
JdbcUtil.safeClose(rs);
}
eacs.waitUntilAllCompleted();
if (eacs.isExceptionThrown()) {
releaseLocks(emptyBuckets);
}
if (emptyBuckets.isEmpty())
return;