b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

java threadlocal实例 Spring 中的 Java 基础(1)

电脑杂谈  发布时间:2018-02-04 17:09:36  来源:网络整理

threadlocal使用实例_java threadlocal实例_java threadlocal 回收

Spring AOP 使用动态代理技术在运行期织入增强的代码,为了揭示 Spring AOP 底层的工作机理,有必要对涉及到的 Java 知识进行学习。

Spring AOP 使用了两种代理机制:一种是基于JDK的动态代理;另一种是基于CGLib的动态代理。之所以需要两种代理机制,很大程度上是因为 JDK 本身只提供接口的代理,而不支持类的代理。

在调用每一个目标类方法时启动方法的性能监视,在目标类方法调用完成时记录方法的花费时间。

ForumService:包含性能监视横切代码

package com.smart.proxy;

public class ForumServiceImpl implements ForumService {

    public void removeTopic(int topicId) {
        PerformanceMonitor.begin("com.smart.proxy.ForumServiceImpl.removeTopic");
        System.out.println("模拟删除Topic记录:"+topicId);
        try {
            Thread.currentThread().sleep(20);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }       
        PerformanceMonitor.end();
    }

    public void removeForum(int forumId) {
        PerformanceMonitor.begin("com.smart.proxy.ForumServiceImpl.removeForum");
        System.out.println("模拟删除Forum记录:"+forumId);
        try {
            Thread.currentThread().sleep(40);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }       
        PerformanceMonitor.end();
    }
}

每个Service类和每个业务方法体的前后都执行相同的代码逻辑:方法调用前启动PerformanceMonitor,方法调用后通知PerformanceMonitor结束性能监视并给记录性能监视结果。

PerformanceMonitor是性能监视的实现类,我们给出一个非常简单的实现版本

package com.smart.proxy;

public class PerformanceMonitor {
    // 线程本地变量 performaceRecord
    private static ThreadLocal<MethodPerformace> performaceRecord = new ThreadLocal<MethodPerformace>();

    // 开始对某个目标类方法的监视
    public static void begin(String method) {
        System.out.println("begin monitor...");
        MethodPerformace mp = performaceRecord.get();
        if (mp == null) {
            mp = new MethodPerformace(method);
            performaceRecord.set(mp);
        } else {
            mp.reset(method);
        }
    }

    // 结束对某个目标类方法的监视,并给出性能监视信息
    public static void end() {
        System.out.println("end monitor...");
        MethodPerformace mp = performaceRecord.get();
        mp.printPerformace();
    }
}


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-64976-1.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...