Skip to content

Commit feea051

Browse files
committed
[FLINK-32659] Fix the connection leak due to exception
1 parent e3c52a4 commit feea051

File tree

1 file changed

+23
-20
lines changed

1 file changed

+23
-20
lines changed

flink-connector-jdbc/src/main/java/org/apache/flink/connector/jdbc/internal/JdbcOutputFormat.java

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -249,33 +249,36 @@ protected void attemptFlush() throws SQLException {
249249
/** Executes prepared statement and closes all resources of this instance. */
250250
@Override
251251
public synchronized void close() {
252-
if (!closed) {
253-
closed = true;
252+
try {
253+
if (!closed) {
254+
closed = true;
254255

255-
if (this.scheduledFuture != null) {
256-
scheduledFuture.cancel(false);
257-
this.scheduler.shutdown();
258-
}
256+
if (this.scheduledFuture != null) {
257+
scheduledFuture.cancel(false);
258+
this.scheduler.shutdown();
259+
}
259260

260-
if (batchCount > 0) {
261-
try {
262-
flush();
263-
} catch (Exception e) {
264-
LOG.warn("Writing records to JDBC failed.", e);
265-
throw new RuntimeException("Writing records to JDBC failed.", e);
261+
if (batchCount > 0) {
262+
try {
263+
flush();
264+
} catch (Exception e) {
265+
LOG.warn("Writing records to JDBC failed.", e);
266+
throw new RuntimeException("Writing records to JDBC failed.", e);
267+
}
266268
}
267-
}
268269

269-
try {
270-
if (jdbcStatementExecutor != null) {
271-
jdbcStatementExecutor.closeStatements();
270+
try {
271+
if (jdbcStatementExecutor != null) {
272+
jdbcStatementExecutor.closeStatements();
273+
}
274+
} catch (SQLException e) {
275+
LOG.warn("Close JDBC writer failed.", e);
272276
}
273-
} catch (SQLException e) {
274-
LOG.warn("Close JDBC writer failed.", e);
275277
}
278+
} finally {
279+
connectionProvider.closeConnection();
280+
checkFlushException();
276281
}
277-
connectionProvider.closeConnection();
278-
checkFlushException();
279282
}
280283

281284
public static Builder builder() {

0 commit comments

Comments
 (0)