ThreadLocal源代码2_hibernate

ThreadLocal源代码2_ThreadLocal_02

ThreadLocal源代码2_hibernate_03

ThreadLocal源代码2_业务逻辑_04

ThreadLocal源代码2_hibernate_05

private static int nextIndex(int i, int len) {
    return ((i + 1 < len) ? i + 1 : 0);
}
private static int prevIndex(int i, int len) {
    return ((i - 1 >= 0) ? i - 1 : len - 1);
}

ThreadLocal源代码2_业务逻辑_06

ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
try {
    threadLocal.set(new Session(1, "Misout的博客"));
    // 其它业务逻辑
} finally {
    threadLocal.remove();
}
//还记得Hibernate的session获取场景吗?
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
//获取Session
public static Session getCurrentSession(){
    Session session =  threadLocal.get();
    //判断Session是否为空,如果为空,将创建一个session,并设置到本地线程变量中
    try {
        if(session ==null&&!session.isOpen()){
            if(sessionFactory==null){
                rbuildSessionFactory();// 创建Hibernate的SessionFactory
            }else{
                session = sessionFactory.openSession();
            }
        }
        threadLocal.set(session);
    } catch (Exception e) {
        // TODO: handle exception
    }
 
    return session;
}

ThreadLocal源代码2_java_07

ThreadLocal源代码2_业务逻辑_08

 ThreadLocal源代码2_java_09

ThreadLocal源代码2_java_10

ThreadLocal源代码2_ide_11

 ThreadLocal源代码2_ide_12

ThreadLocal源代码2_ThreadLocal_13

ThreadLocal源代码2_ide_14

ThreadLocal源代码2_业务逻辑_15

ThreadLocal源代码2_hibernate_16

ThreadLocal源代码2_hibernate_17

ThreadLocal源代码2_ide_18

ThreadLocal源代码2_ThreadLocal_19

ThreadLocal源代码2_业务逻辑_20

ThreadLocal源代码2_业务逻辑_21

ThreadLocal源代码2_java_22

ThreadLocal源代码2_ide_23

public class MultiThreadDemo { 
    public static void main(String[] args) throws InterruptedException {
        private int value = 0;
        Thread increaseThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    value = 10;
                    Thread.sleep(10);
                    System.out.println("increase value: " + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread decreaseThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    value = -10;
                    Thread.sleep(10);
                    System.out.println("decrease value: " + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        increaseThread.start();
        decreaseThread.start();
    }
}

ThreadLocal源代码2_业务逻辑_24

public class SimpleImpl {  

    public static void main(String[] args) throws InterruptedException {
        private Map<Long, Integer> cacheMap = new HashMap<>();
        private int defaultValue = 0 ;
        
        Thread increaseThread = new Thread(new Runnable() {
            @Override
            public void run() { 
                long id = Thread.currentThread().getId();
                cacheMap.put(id, 10); 
                Thread.sleep(10);
                long id = Thread.currentThread().getId();
                if (cacheMap.containsKey(id)) {
                    return cacheMap.get(id);
                }
                return defaultValue; 
            }
        });

        Thread decreaseThread = new Thread(new Runnable() {
            @Override
            public void run() {
                long id = Thread.currentThread().getId();
                cacheMap.put(id, -10);
                Thread.sleep(10);
                long id = Thread.currentThread().getId();
                if (cacheMap.containsKey(id)) {
                    return cacheMap.get(id);
                }
                return defaultValue;
            }
        });

        increaseThread.start();
        decreaseThread.start();
    }
}

ThreadLocal源代码2_ThreadLocal_25

public class SimpleImpl2 {

    public static class CommonThread extends Thread {
        Map<Integer, Integer> cacheMap = new HashMap<>();
    } 

    public static class Number {  
        public void increase() throws InterruptedException {
             Integer id = this.hashCode();
            Map<Integer, Integer> cacheMap = (CommonThread) Thread.currentThread().cacheMap;
            cacheMap.put(id, 10);
            Thread.sleep(10);  
            return cacheMap.get(id); 
        }

        public void decrease() throws InterruptedException {
            Integer id = this.hashCode();
            Map<Integer, Integer> cacheMap = (CommonThread) Thread.currentThread().cacheMap;
            cacheMap.put(id, -10);
            Thread.sleep(10);   
            return cacheMap.get(id); 
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final Number number = new Number();
        Thread increaseThread = new CommonThread() {
            @Override
            public void run() { 
                number.increase(); 
            }
        };

        Thread decreaseThread = new CommonThread() {
            @Override
            public void run() { 
                number.decrease(); 
            }
        };
        increaseThread.start();
        decreaseThread.start();
    }
}

在上面的实现中,当线程消亡之后,线程中 cacheMap 也会被回收,它当中存放的副本变量(value)也会被全部回收,并且 cacheMap 是线程私有的,不会出现多个线程同时访问一个 cacheMap 的情况。在 Java 中,ThreadLocal 类的实现就是采用的这种思想,注意只是思想,实际的实现和上面的并不一样。

 ThreadLocal源代码2_java_26

ThreadLocal源代码2_业务逻辑_27

ThreadLocal源代码2_ThreadLocal_28

ThreadLocal源代码2_ide_29

ThreadLocal源代码2_hibernate_30

ThreadLocal源代码2_ThreadLocal_31

ThreadLocal源代码2_hibernate_32

ThreadLocal源代码2_java_33

ThreadLocal源代码2_java_34

ThreadLocal源代码2_ide_35

ThreadLocal源代码2_业务逻辑_36

ThreadLocal源代码2_业务逻辑_37

ThreadLocal源代码2_java_38

ThreadLocal源代码2_ThreadLocal_39

ThreadLocal源代码2_hibernate_40