Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JDBC 라이브러리 구현하기 - 4단계] 이리내(성채연) 미션 제출합니다. #588

Merged
merged 8 commits into from
Oct 12, 2023
31 changes: 31 additions & 0 deletions jdbc/src/main/java/org/springframework/jdbc/ConnectionHolder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.springframework.jdbc;

import static java.util.Objects.isNull;

import java.sql.Connection;

public class ConnectionHolder {

private Connection connection;
private boolean transactionActive = false;

public ConnectionHolder(final Connection connection) {
this.connection = connection;
Comment on lines +6 to +13

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코멘트에 남겨주신것처럼 커넥션 홀더를 적용해주셨네요! 감동1

}

public void setTransactionActive(final boolean transactionActive) {
this.transactionActive = transactionActive;
}

public boolean isTransactionActive() {
return transactionActive;
}

public Connection getConnection() {
return connection;
}

public boolean has(final Connection connection) {
return this.connection == connection;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ private <T> T execute(final PreparedStatementCallback preparedStatementCallback,
return executionCallback.execute(pstmt);
} catch (SQLException e) {
throw new DataAccessException(e);
} finally {
DataSourceUtils.releaseConnection(connection, dataSource);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package org.springframework.jdbc.datasource;

import static java.util.Objects.isNull;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.ConnectionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
Expand All @@ -13,22 +17,57 @@ public abstract class DataSourceUtils {
private DataSourceUtils() {}

public static Connection getConnection(final DataSource dataSource) throws CannotGetJdbcConnectionException {
Connection connection = TransactionSynchronizationManager.getResource(dataSource);
if (connection != null) {
return connection;
final ConnectionHolder connectionHolder = TransactionSynchronizationManager.getResource(dataSource);
if (connectionHolder != null) {
return connectionHolder.getConnection();
}

try {
connection = dataSource.getConnection();
final Connection connection = dataSource.getConnection();
TransactionSynchronizationManager.bindResource(dataSource, connection);
return connection;
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection", ex);
}
}

public static void startTransaction(final Connection connection, final DataSource dataSource) {
final ConnectionHolder connectionHolder = getConnectionHolder(connection, dataSource);
try{
connectionHolder.setTransactionActive(true);
connection.setAutoCommit(false);
}catch(SQLException e) {
throw new DataAccessException();
}
}

private static ConnectionHolder getConnectionHolder(final Connection connection, final DataSource dataSource) {
final ConnectionHolder connectionHolder = TransactionSynchronizationManager.getResource(dataSource);
if(isNull(connectionHolder)) {
throw new IllegalStateException();
}
if(!connectionHolder.has(connection)) {
throw new IllegalStateException();
}
return connectionHolder;
}

public static void finishTransaction(final Connection connection, final DataSource dataSource) {
final ConnectionHolder connectionHolder = getConnectionHolder(connection, dataSource);
try{
connection.commit();
connectionHolder.setTransactionActive(false);
}catch(SQLException e) {
throw new DataAccessException();
}
}

public static void releaseConnection(final Connection connection, final DataSource dataSource) {
try {
final ConnectionHolder connectionHolder = getConnectionHolder(connection, dataSource);
if(connectionHolder.isTransactionActive()) {
return;
}
TransactionSynchronizationManager.unbindResource(dataSource);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

connection.close(); 에서 예외가 발생하더라도
TransactionSynchronizationManager.unbindResource(dataSource);가 일어날 수 있도록 하는것이 좋을까요? 예외가 발생하면 일어나지 않도록 하는것이 좋을까요? 저도 고민이 되었었는데 이리내와 얘기를 나눠보고싶네요!

Copy link
Author

@hectick hectick Oct 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그러게요 생각해보지 못했는데 고민할만한 내용인 것 같습니다
생각해보니 저라면 unbind 해줄 것 같아요
쓰레드가 재사용되는 상황이라면, 이전 Connection이 비워지지 않고 남아있으면 위험하지 않을까요??

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저또한 예외가 발생하더라도 비워주는것이 현재코드로서는 안전하다는 생각이 드네요
저같은 경우는 final로 처리를 하였는데 여기 순서를 변경하는 방법으로 구현하셨군요~!이런 방법도 있네요!?

connection.close();
} catch (SQLException ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ public TransactionExecutor(final DataSource dataSource) {
public <T> T execute(final Supplier<T> supplier) {
final Connection connection = DataSourceUtils.getConnection(dataSource);
try {
connection.setAutoCommit(false);
DataSourceUtils.startTransaction(connection, dataSource);
final T t = supplier.get();
connection.commit();
DataSourceUtils.finishTransaction(connection, dataSource);
return t;
} catch (SQLException | DataAccessException e) {
} catch (DataAccessException e) {
rollback(connection);
throw new DataAccessException(e);
} finally {
Expand All @@ -33,10 +33,10 @@ public <T> T execute(final Supplier<T> supplier) {
public void execute(final Runnable runnable) {
final Connection connection = DataSourceUtils.getConnection(dataSource);
try {
connection.setAutoCommit(false);
DataSourceUtils.startTransaction(connection, dataSource);
runnable.run();
connection.commit();
} catch (SQLException | DataAccessException e) {
DataSourceUtils.finishTransaction(connection, dataSource);
} catch (DataAccessException e) {
rollback(connection);
throw new DataAccessException(e);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,32 @@
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Map;
import org.springframework.jdbc.ConnectionHolder;

public abstract class TransactionSynchronizationManager {

private static final ThreadLocal<Map<DataSource, Connection>> resources = ThreadLocal.withInitial(HashMap::new);
private static final ThreadLocal<Map<DataSource, ConnectionHolder>> resources = ThreadLocal.withInitial(HashMap::new);

private TransactionSynchronizationManager() {}

@Nullable
public static Connection getResource(final DataSource key) {
public static ConnectionHolder getResource(final DataSource key) {
return getResources().getOrDefault(key, null);
}

public static void bindResource(final DataSource key, final Connection value) {
getResources().put(key, value);
final Map<DataSource, ConnectionHolder> resources = getResources();
if(resources.containsKey(key)){
throw new IllegalStateException();
}
resources.put(key, new ConnectionHolder(value));
}

public static Connection unbindResource(final DataSource key) {
public static ConnectionHolder unbindResource(final DataSource key) {
return getResources().remove(key);
}

private static Map<DataSource, Connection> getResources() {
private static Map<DataSource, ConnectionHolder> getResources() {
return resources.get();
}
}
Loading