众所周知,从以前的jbpm到现今的activiti,流程引擎的内部执行模式是command模式,不管是启动流程,还是推动流程等等,都采用了command的execute方法。而command执行依赖于CommandContext,直译就是command的上下文,那么,我们就来看看CommandContext里面的内容。
首先是CommandContext本身的类变量和实例变量:
private static Logger log = Logger.getLogger(CommandContext.class.getName());
private static final ThreadLocal<Stack<CommandContext>> txContextStacks = new ThreadLocal<Stack<CommandContext>>();
protected Command< ? > command;
protected TransactionContext transactionContext;
protected Map<Class< ? >, Session> sessions = new HashMap<Class< ? >, Session>();
protected Throwable exception = null;
protected ProcessEngineConfigurationImpl processEngineConfiguration;
其实从这个变量声明,我们就能够大致看出CommandContext的管辖范围,首先是提供线程安全的副本栈txContextStacks,然后是在当前上下文执行的command,事务上下文transactionContext,会话集合sessions ,流程引擎配置类processEngineConfiguration,至于log和exception肯定就不用说了。当然,实际来说,transactionContext其实只是为session管理服务的,稍后可见。
为了避免线程冲突,每个command都在一个独立的commandContext中执行,如下:
public static void setCurrentCommandContext(CommandContext commandContext) {
getContextStack(true).push(commandContext);
}
public static void removeCurrentCommandContext() {
getContextStack(true).pop();
}
public static CommandContext getCurrent() {
Stack<CommandContext> contextStack = getContextStack(false);
&

本文介绍了Activiti流程引擎中的CommandContext,它是流程执行的核心。CommandContext维护了线程安全的command执行上下文,包括command、事务、会话和异常信息。通过ThreadLocal的Stack管理CommandContext的生命周期,确保每个command在独立的上下文中执行。CommandInterceptor负责创建和关闭CommandContext,同时管理会话的提交、回滚和关闭,以及事务处理。此外,CommandContext还提供了获取不同类型会话的方法。
最低0.47元/天 解锁文章
1616





