|
| 1 | +package com.conveyal.gtfs.loader; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | + |
| 6 | +import java.sql.PreparedStatement; |
| 7 | +import java.sql.SQLException; |
| 8 | + |
| 9 | +/** |
| 10 | + * Avoid Java's "effectively final" nonsense when using prepared statements in foreach loops. |
| 11 | + * Automatically push execute batches of prepared statements before the batch gets too big. |
| 12 | + * TODO there's probably something like this in an Apache Commons util library |
| 13 | + */ |
| 14 | +public class BatchTracker { |
| 15 | + private static final Logger LOG = LoggerFactory.getLogger(BatchTracker.class); |
| 16 | + |
| 17 | + private final String recordType; |
| 18 | + private PreparedStatement preparedStatement; |
| 19 | + private int currentBatchSize = 0; |
| 20 | + private int totalRecordsProcessed = 0; |
| 21 | + |
| 22 | + public BatchTracker(String recordType, PreparedStatement preparedStatement) { |
| 23 | + this.preparedStatement = preparedStatement; |
| 24 | + this.recordType = recordType; |
| 25 | + } |
| 26 | + |
| 27 | + public void addBatch() throws SQLException { |
| 28 | + preparedStatement.addBatch(); |
| 29 | + currentBatchSize += 1; |
| 30 | + if (currentBatchSize > JdbcGtfsLoader.INSERT_BATCH_SIZE) { |
| 31 | + preparedStatement.executeBatch(); |
| 32 | + totalRecordsProcessed += currentBatchSize; |
| 33 | + currentBatchSize = 0; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + public void executeRemaining() throws SQLException { |
| 38 | + if (currentBatchSize > 0) { |
| 39 | + totalRecordsProcessed += currentBatchSize; |
| 40 | + preparedStatement.executeBatch(); |
| 41 | + currentBatchSize = 0; |
| 42 | + } |
| 43 | + // Avoid reuse, signal that this was cleanly closed. |
| 44 | + preparedStatement = null; |
| 45 | + LOG.info(String.format("Inserted %d %s records", totalRecordsProcessed, recordType)); |
| 46 | + } |
| 47 | + |
| 48 | + public void finalize () { |
| 49 | + if (preparedStatement != null || currentBatchSize > 0) { |
| 50 | + throw new RuntimeException("BUG: It looks like someone did not call executeRemaining on a BatchTracker."); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments