【Spring事务详解】--- 5.事务管理器TransactionSynchronizationManager分析

前言

Spring事务详解连载

【Spring事务详解】— 1.事务传播的案例演示
【Spring事务详解】— 2.事务应用的注意事项
【Spring事务详解】— 3.事务失效的八种场景
【Spring事务详解】— 4.事务管理器的架构分析
【Spring事务详解】— 5.事务管理器TransactionSynchronizationManager分析
【Spring事务详解】— 6.事务创建的流程分析
【Spring事务详解】— 7.事务提交、回滚的流程分析
【Spring事务详解】— 8.beforeCommit、beforeCompletion、afterCommit、afterCompletion实现分析

TransactionSynchronizationManager主要作用就是管理每个线程的资源和事务同步,包括资源绑定,激活事务同步等。

6个ThreadLocal

TransactionSynchronizationManager中定义了6个ThreadLocal对象,单从名称就能分析出来,他们分别负责维护:事务资源、事务同步,事务名称、事务只读状态、事务隔离级别以及当前事务是否活跃。

private static final ThreadLocal<Map<Object, Object>> resources =
		new NamedThreadLocal<>("Transactional resources");
private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations =
		new NamedThreadLocal<>("Transaction synchronizations");
private static final ThreadLocal<String> currentTransactionName =
		new NamedThreadLocal<>("Current transaction name");
private static final ThreadLocal<Boolean> currentTransactionReadOnly =
		new NamedThreadLocal<>("Current transaction read-only status");
private static final ThreadLocal<Integer> currentTransactionIsolationLevel =
		new NamedThreadLocal<>("Current transaction isolation level");
private static final ThreadLocal<Boolean> actualTransactionActive =
		new NamedThreadLocal<>("Actual transaction active");

事务资源

对于事务资源,TransactionSynchronizationManager中负责提供资源获取、绑定、解绑等接口

获取资源

/**
 * Retrieve a resource for the given key that is bound to the current thread.
 * @param key the key to check (usually the resource factory)
 * @return a value bound to the current thread (usually the active
 * resource object), or {@code null} if none
 * @see ResourceTransactionManager#getResourceFactory()
 */
@Nullable
public static Object getResource(Object key) {
	Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
	return doGetResource(actualKey);
}
/**
 * Actually check the value of the resource that is bound for the given key.
 */
@Nullable
private static Object doGetResource(Object actualKey) {
	Map<Object, Object> map = resources.get();
	if (map == null) {
		return null;
	}
	Object value = map.get(actualKey);
	// Transparently remove ResourceHolder that was marked as void...
	if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
		map.remove(actualKey);
		// Remove entire ThreadLocal if empty...
		if (map.isEmpty()) {
			resources.remove();
		}
		value = null;
	}
	return value;
}

绑定资源

public static void bindResource(Object key, Object value) throws IllegalStateException {
	Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
	Assert.notNull(value, "Value must not be null");
	Map<Object, Object> map = resources.get();
	// set ThreadLocal Map if none found
	if (map == null) {
		map = new HashMap<>();
		resources.set(map);
	}
	Object oldValue = map.put(actualKey, value);
	// Transparently suppress a ResourceHolder that was marked as void...
	if (oldValue instanceof ResourceHolder && ((ResourceHolder) oldValue).isVoid()) {
		oldValue = null;
	}
	if (oldValue != null) {
		throw new IllegalStateException(
				"Already value [" + oldValue + "] for key [" + actualKey + "] bound to thread");
	}
}

解绑资源

public static Object unbindResource(Object key) throws IllegalStateException {
	Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
	Object value = doUnbindResource(actualKey);
	if (value == null) {
		throw new IllegalStateException("No value for key [" + actualKey + "] bound to thread");
	}
	return value;
}
@Nullable
private static Object doUnbindResource(Object actualKey) {
	Map<Object, Object> map = resources.get();
	if (map == null) {
		return null;
	}
	Object value = map.remove(actualKey);
	// Remove entire ThreadLocal if empty...
	if (map.isEmpty()) {
		resources.remove();
	}
	// Transparently suppress a ResourceHolder that was marked as void...
	if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
		value = null;
	}
	return value;
}

事务同步

对于事务同步,TransactionSynchronizationManager中负责提供:事务同步激活、事务同步注册、获取事务同步列表、判断当前事务同步是否为活跃的等。

事务同步激活

实际上就是给synchronizations放入一个LinkedHashSet

public static void initSynchronization() throws IllegalStateException {
	if (isSynchronizationActive()) {
		throw new IllegalStateException("Cannot activate transaction synchronization - already active");
	}
	synchronizations.set(new LinkedHashSet<>());
}

事务同步注册

从当前线程中取出set集合,并为其添加一个TransactionSynchronization对象

public static void registerSynchronization(TransactionSynchronization synchronization)
		throws IllegalStateException {
	Assert.notNull(synchronization, "TransactionSynchronization must not be null");
	Set<TransactionSynchronization> synchs = synchronizations.get();
	if (synchs == null) {
		throw new IllegalStateException("Transaction synchronization is not active");
	}
	synchs.add(synchronization);
}

获取事务同步列表

public static List<TransactionSynchronization> getSynchronizations() throws IllegalStateException {
	Set<TransactionSynchronization> synchs = synchronizations.get();
	if (synchs == null) {
		throw new IllegalStateException("Transaction synchronization is not active");
	}
	// Return unmodifiable snapshot, to avoid ConcurrentModificationExceptions
	// while iterating and invoking synchronization callbacks that in turn
	// might register further synchronizations.
	if (synchs.isEmpty()) {
		return Collections.emptyList();
	}
	else {
		// Sort lazily here, not in registerSynchronization.
		List<TransactionSynchronization> sortedSynchs = new ArrayList<>(synchs);
		OrderComparator.sort(sortedSynchs);
		return Collections.unmodifiableList(sortedSynchs);
	}
}

判断当前事务是否为活跃

public static boolean isSynchronizationActive() {
	return (synchronizations.get() != null);
}

currentTransactionReadOnly和currentTransactionIsolationLevel

这两个属性分别记录当前线程事务是否只读状态和其隔离级别

public static void setCurrentTransactionReadOnly(boolean readOnly) {
	currentTransactionReadOnly.set(readOnly ? Boolean.TRUE : null);
}
public static void setCurrentTransactionIsolationLevel(@Nullable Integer isolationLevel) {
	currentTransactionIsolationLevel.set(isolationLevel);
}

actualTransactionActive

actualTransactionActive用于记录当前线程是否有实际活动的事务,

public static void setActualTransactionActive(boolean active) {
	actualTransactionActive.set(active ? Boolean.TRUE : null);
}

isSynchronizationActive相比,线程可能存在活跃的事务,但如果当前线程的事务被挂起,那么就不是实际活跃的事务了,所以对于被挂起的线程调用isSynchronizationActive返回true,调用isActualTransactionActive则返回false

public static boolean isActualTransactionActive() {
	return (actualTransactionActive.get() != null);
}

清除

最后,事务提交后,TransactionSynchronizationManager提供了清除当前线程事务同步数据的方法。

public static void clear() {
	synchronizations.remove();
	currentTransactionName.remove();
	currentTransactionReadOnly.remove();
	currentTransactionIsolationLevel.remove();
	actualTransactionActive.remove();
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码拉松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值