Curriculum design patterns Design patterns succinctly 8-10 Singleton Singleton design pattern -ThreadLocal thread

1 The course explains

1.1 application scenarios

2 Code Walkthrough

2.1 threadLocal application

 

 

1 The course explains
1.1 application scenarios

Multithreading time:

Use synchronization lock time for space use, (long thread queue time)

The use threadlocal use space for time approach.

Based on singleton threadlocal provides an object for each thread, multi-threaded access will not affect each other.

ThreadLocal implemented based on single embodiment, this application scenario database connection pool obtained directly increased concurrency, and isolation of the thread, the thread does not lead to a global database disconnection caused disconnection, obtained directly applied to improve the fault tolerance . But the code level to avoid a single case mix different threads generated.

 

Their appreciated: in fact, this embodiment mode single quotation marks (threadLocal) mode has not referred to a single embodiment, a single embodiment because the same class, an object has been taken out is not the same

 

2 Code Walkthrough
2.1 threadLocal application

Test categories:

package com.geely.design.pattern.creational.singleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {

    public static void main(String [] args){
        Thread thread1 = new Thread(new T());
        Thread thread2 = new Thread(new T());
        thread1.start();
        thread2.start();
        System.out.println("结束了!!!");
    }

}

 

Thread class:

package com.geely.design.pattern.creational.singleton;

/**
 * 注:该类为线程类,调用LazySingleton
 */
public class T implements Runnable{

    @Override
    public void run() {
/*        StaticInnerClassSingleton staticInnerClassSingleton = StaticInnerClassSingleton.getInstance();*/
        ThreadLocalInstance threadLocalInstance = ThreadLocalInstance.getInstance();
        System.out.println(Thread.currentThread().getName()+"==="+threadLocalInstance);
    }
}

 

Entity classes:

package com.geely.design.pattern.creational.singleton;

public class ThreadLocalInstance {
    /**
     * 预防外部类 实例化本类
     */
    private  ThreadLocalInstance(){

    }

   public static final ThreadLocal<ThreadLocalInstance> threadLocalInstance
           = new ThreadLocal<ThreadLocalInstance>(){
       /**
        * 重写初始化方法
        */
       @Override
       protected ThreadLocalInstance initialValue(){
           return new ThreadLocalInstance();
        }
   };

    /**
     * 获得实例
     * @return
     */
    public static ThreadLocalInstance getInstance(){
       return threadLocalInstance.get();
    }
}

 

Reference to the class:

  /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }

static class ThreadLocalMap { /** * The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object). Note that null keys (i.e. entry.get() * == null) mean that the key is no longer referenced, so the * entry can be expunged from table. Such entries are referred to * as "stale entries" in the code that follows. */ static class Entry extends WeakReference<ThreadLocal> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal k, Object v) { super(k); value = v; } } }

 

 

Print log:

 

ended! ! ! 
The Thread -0 === com.geely.design.pattern.creational.singleton.ThreadLocalInstance@120f0be 
the Thread -1 === com.geely.design.pattern.creational.singleton.ThreadLocalInstance@75dfb148 

Process Finished Exit with code 0

 

Guess you like

Origin www.cnblogs.com/1446358788-qq/p/11442693.html