`
barryzhong
  • 浏览: 21805 次
  • 性别: Icon_minigender_1
社区版块
存档分类

生命周期组件框架:生命周期描述语言——并发加写锁和解写锁执行过程示例

阅读更多
@StateMachine
    static interface LockingStateMachine {

        @StateSet
        static interface States {

            @Initial
            @Function(transition = LockingStateMachine.Transitions.Start.class, value = Started.class)
            static interface Created {}
            @Functions({ @Function(transition = LockingStateMachine.Transitions.Stop.class, value = Stopped.class),
                    @Function(transition = LockingStateMachine.Transitions.Cancel.class, value = Canceled.class) })
            static interface Started {}
            @End
            static interface Stopped {}
            @End
            static interface Canceled {}
        }
        @TransitionSet
        static interface Transitions {

            static interface Start {}
            static interface Stop {}
            static interface Cancel {}
        }
    }
    static interface ILockingReactiveObject {

        public abstract int getCounter();

        public abstract void start();

        public abstract void stop();

        public abstract void cancel();
    }

 
   

public static class SimpleLock implements LifecycleLockStrategry {

        private static Logger logger = Logger.getLogger("Lifecycle Framework");
        private static volatile int depth = 0;
        private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

        @Override
        public void lockRead(Object reactiveObject) {
            logLockingMethod(reactiveObject, "lockRead: ");
            lock.readLock().lock();
            depth++;
        }

        private void logLockingMethod(Object reactiveObject, String methodName) {
            final StringBuilder builder = getIndent();
            builder.append(methodName + reactiveObject);
            logger.fine(builder.toString());
        }

        private StringBuilder getIndent() {
            StringBuilder builder = new StringBuilder();
            for ( int i = 0; i  klass) throws Throwable {
        final ExecutorService executorService = Executors.newFixedThreadPool(7);
        for ( int i = 0; i  c1 = new Callable() {

                @Override
                public LifecycleException call() throws Exception {
                    try {
                        object.stop();
                        return null;
                    } catch (LifecycleException e) {
                        return e;
                    }
                }
            };
            Callable c2 = new Callable() {

                @Override
                public LifecycleException call() throws Exception {
                    try {
                        object.cancel();
                        return null;
                    } catch (LifecycleException e) {
                        return e;
                    }
                }
            };
            if ( i % 2 == 0 ) {
                Callable temp = c1;
                c1 = c2;
                c2 = temp;
            }
            final Future f1 = executorService.submit(c1);
            final Future f2 = executorService.submit(c2);
            final Callable c3 = new Callable() {

                @Override
                public Exception call() throws Exception {
                    try {
                        final LifecycleException e1 = f1.get();
                        final LifecycleException e2 = f2.get();
                        assertFalse(( null != e1 && null != e2 ) || ( null == e1 && null == e2 ));
                        final LifecycleException e = null != e1 ? e1 : e2;
                        System.out.println(e.toString());
                        assertEquals(LifecycleCommonErrors.ILLEGAL_TRANSITION_ON_STATE, e.getErrorCode());
                        assertEquals(2, object.getCounter());
                        return null;
                    } catch (Exception e) {
                        return e;
                    }
                }
            };
            final Future f3 = executorService.submit(c3);
            if ( null != f3.get() ) {
                fail(f3.get().getMessage());
            }
        }
    }

 
日志截屏如下(请点击放大)


 

日志解释:
执行过程中的加(获取)写锁和解(释放)写锁的过程

[FINE]: Found Intercept Point: class net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject.start( )
[FINE]: Intercepting....instatiating InterceptContext ...

[FINE]: Intercepting....InterceptorController is doing exec ...

[FINE]: Intercepting....instantiating LifecycleInterceptor

[FINE]: intercepting with :net.madz.bcel.intercept.LifecycleInterceptor @preExec

[FINE]: lockWrite: net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@62b9f149

[FINE]: intercepting [net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@62b9f149]
from state: [Created]
[FINE]: Step 1. start validating State [Created]
[FINE]: Step 2. start validating transition: [Start] on state: [Created]
[FINE]: Step 3. start validating inbound relation constraint is next state is predictable before method invocation.
[FINE]: Step 4. start callback before state change from : Created => to : Started

[FINE]: intercepting with: net.madz.bcel.intercept.CallableInterceptor @intercept

[FINE]: intercepting with :net.madz.bcel.intercept.LifecycleInterceptor @postExec

[FINE]: Step 5. start validating inbound relation constraint is next state after method invocation.
[FINE]: Step 6. Set next state to reactiveObject.
[FINE]: Step 6. ReactiveObject is tranisited to state: [Started]
[FINE]: Step 7. Start Callback after state change from : Created => to : Started

[FINE]: unlockWrite: net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@62b9f149

[FINE]: Step 8. Start fire state change event.

[FINE]: intercepting with :net.madz.bcel.intercept.LifecycleInterceptor @cleanup

[FINE]: Intercepting....LifecycleInterceptor is doing cleanup ...

并发执行同步过程日志

//线程一开始获取写锁
[FINE]: lockWrite: net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@31c1fb39
//线程二开始获取写锁
[FINE]: lockWrite: net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@31c1fb39
//线程一得到写锁并继续执行生命周期引擎
[FINE]: intercepting  [net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@31c1fb39]
from state: [Started]
[FINE]: Step 1. start validating State [Started]
[FINE]: Step 2. start validating transition: [Stop] on state: [Started]
[FINE]: Step 3. start validating inbound relation constraint is next state is predictable before method invocation.
[FINE]: Step 4. start callback before state change from : Started => to : Stopped

[FINE]: intercepting with: net.madz.bcel.intercept.CallableInterceptor @intercept

[FINE]: intercepting with :net.madz.bcel.intercept.LifecycleInterceptor @postExec

[FINE]: Step 5. start validating inbound relation constraint is next state after method invocation.
[FINE]: Step 6. Set next state to reactiveObject.
[FINE]: Step 6. ReactiveObject is tranisited to state: [Stopped]
[FINE]: Step 7. Start Callback after state change from : Started => to : Stopped
//第一线程执行完Transition开始解写锁
[FINE]: unlockWrite: net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@31c1fb39

[FINE]: Step 8. Start fire state change event.
//线程二得到写锁开始执行引擎
[FINE]: intercepting  [net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@31c1fb39]
from state: [Stopped] //此时状态已经变为Stopped,线程一导致的变化至此已被线程二看见

[FINE]: intercepting with :net.madz.bcel.intercept.LifecycleInterceptor @cleanup

[FINE]: Step 1. start validating State [Stopped]
[FINE]: Intercepting....LifecycleInterceptor is doing cleanup ...
[FINE]: Step 2. start validating transition: [Cancel] on state: [Stopped]

[FINE]: intercepting with :net.madz.bcel.intercept.LifecycleInterceptor @cleanup

[FINE]: Intercepting....LifecycleInterceptor is doing cleanup ...
[SEVERE]: ReactiveObject: [net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@31c1fb39] was failed to transit from state: [Stopped] to state: [(Had Not Been Evaluated)] with following error:
//由于在执行过程中另一线程导致状态发生变化,而使得本线程的Transition不合法
[SEVERE]: Illegal Request Found on object net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@31c1fb39: Transition Cancel is not allowed while object is on Stopped state. 
//线程二Transition失败后开始释放写[FINE]: unlockWrite: net.madz.lifecycle.engine.LifecycleLockTestMetadata$SimpleLockingReactiveObject@31c1fb39

前文:生命周期组件框架:关系型状态机服务

 

  • 大小: 440.1 KB
分享到:
评论

相关推荐

    COM原理与应用 代码

    3. 双向引用计数:COM使用双向引用计数来管理组件生命周期。当组件的引用计数变为0时,该组件会被自动释放,从而避免内存泄漏。 4. 异步通信:COM支持同步和异步调用,允许组件在不同线程或进程中执行,提高了系统...

    c#25个问题的附件.rar

    18. **多线程与并发**:C#的Thread和Task类,以及锁、 Monitor、Semaphore等同步原语,用于管理并发执行。 19. **单元测试**:利用NUnit、xUnit等库进行单元测试,确保代码质量。 20. **NuGet包管理**:NuGet允许...

    Developing.Series.60.Applications 例子源码

    3. 了解如何使用Symbian的内存管理和对象生命周期管理。 4. 熟悉多线程编程,实现并发任务和同步机制。 5. 探索网络编程,如HTTP通信、TCP/IP连接等。 6. 学习数据库访问,如使用本地SQLlite数据库进行数据存储和...

    httpsqs-1.3.tar.gz_linux 消息队列_消息队列

    与其他IPC机制(如共享内存、管道等)相比,消息队列具有独立于进程的生命周期,可以跨进程、跨网络传输,并且提供了消息的顺序保证。 三、httpsqs-1.3的特点 1. **高可用性**:httpsqs-1.3设计了容错机制,确保在...

    JAVA实验报告

    - **ExecutorService**:定义了一组方法来管理线程的生命周期,包括启动、终止以及提交新任务。 - **ThreadPoolExecutor**:是`ExecutorService`的一个具体实现,提供了更灵活的配置选项,如线程数量、队列策略等。 ...

    百度持续交付项目组面试题

    当一个线程访问某个对象的一个`synchronized`方法时,它就获得了该对象的锁,并执行该`synchronized`方法;其他线程若试图访问此对象的任何`synchronized`方法,都会被阻塞,直到第一个线程执行完该方法。 **...

    event_emitter.cr:用于Crystal的惯用异步事件驱动的体系结构

    - 使用弱引用避免内存泄漏,尤其是当监听器生命周期长于事件发射器时。 - 考虑异常处理,确保在事件处理过程中发生的错误不会导致整个应用程序崩溃。 7. **与其他框架集成** - `event_emitter.cr` 可以与其他 ...

    ControlIt-开源

    通过智能的内存分配策略,开发者不必手动管理对象的生命周期,从而减少了内存泄漏和资源浪费的可能性。这使得开发者可以更加专注于业务逻辑,而不是底层细节。 4. **客户端/服务器架构**:ControlIt 的设计基于...

Global site tag (gtag.js) - Google Analytics