另一鲜为人知的单例写法-ThreadLocal
另一鲜为人知的单例写法-ThreadLocal
源代码范例
当我阅读FocusFinder和Choreographer的时候,我发现这两类的单例实现和我们寻经常使用双重检查锁非常不一样。而是用来一个ThreadLocal。这个也能够实现单例啊,那这个与双重检查锁实现的单例有什么差别呢?
1.FocusFinder
/**
* The algorithm used for finding the next focusable view in a given direction
* from a view that currently has focus.
*/
public class FocusFinder {
private static final ThreadLocal<FocusFinder> tlFocusFinder =
new ThreadLocal<FocusFinder>() {
@Override
protected FocusFinder initialValue() {
return new FocusFinder();
}
};
/**
* Get the focus finder for this thread.
*/
public static FocusFinder getInstance() {
return tlFocusFinder.get();
}
// enforce thread local access
private FocusFinder() {}
}
2.Choreographer
public final class Choreographer {
// Thread local storage for the choreographer.
private static final ThreadLocal<Choreographer> sThreadInstance =
new ThreadLocal<Choreographer>() {
@Override
protected Choreographer initialValue() {
Looper looper = Looper.myLooper();
if (looper == null) {
throw new IllegalStateException("The current thread must have a looper!");
}
return new Choreographer(looper);
}
};
private Choreographer(Looper looper) {
mLooper = looper;
mHandler = new FrameHandler(looper);
mDisplayEventReceiver = USE_VSYNC ?
new FrameDisplayEventReceiver(looper) : null;
mLastFrameTimeNanos = Long.MIN_VALUE;
mFrameIntervalNanos = (long)(1000000000 / getRefreshRate());
mCallbackQueues = new CallbackQueue[CALLBACK_LAST + 1];
for (int i = 0; i <= CALLBACK_LAST; i++) {
mCallbackQueues[i] = new CallbackQueue();
}
}
/**
* Gets the choreographer for the calling thread. Must be called from
* a thread that already has a {@link android.os.Looper} associated with it.
*
* @return The choreographer for this thread.
* @throws IllegalStateException if the thread does not have a looper.
*/
public static Choreographer getInstance() {
return sThreadInstance.get();
}
}
理论分析
ThreadLocal会为每个线程提供一个独立的变量副本,从而隔离了多个线程对数据的訪问冲突。
对于多线程资源共享的问题,同步机制採用了“以时间换空间”的方式,而ThreadLocal採用了“以空间换时间”的方式。前者仅提供一份变量,让不同的线程排队訪问,而后者为每个线程都提供了一份变量。因此能够同一时候訪问而互不影响。
public class ThreadLocal{
/**
* Provides the initial value of this variable for the current thread.
* The default implementation returns {@code null}.
*
* @return the initial value of the variable.
*/
protected T initialValue() {
return null;
}
/**
* Returns the value of this variable for the current thread. If an entry
* doesn't yet exist for this variable on this thread, this method will
* create an entry, populating the value with the result of
* {@link #initialValue()}.
*
* @return the current value of the variable for the calling thread.
*/
@SuppressWarnings("unchecked")
public T get() {
// Optimized for the fast path.
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values != null) {
Object[] table = values.table;
int index = hash & values.mask;
if (this.reference == table[index]) {
return (T) table[index + 1];
}
} else {
values = initializeValues(currentThread);
}
return (T) values.getAfterMiss(this);
}
/**
* Gets Values instance for this thread and variable type.
*/
Values values(Thread current) {
return current.localValues;
}
/**
* Sets the value of this variable for the current thread. If set to
* {@code null}, the value will be set to null and the underlying entry will
* still be present.
*
* @param value the new value of the variable for the caller thread.
*/
public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}
}
实现步骤
//1.initialValue,创建ThreadLocal对象
//2.get(),获取当前线程里的values
//3.假设不存在则初始化一个空的values
//4.假设存在,则复用values
另一处经典应用
在Looper中使用ThreadLocal,使之每个Thread都有一个Looper与之相应.
public class Looper{
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
}
自己也写
public class Manager {
private static final ThreadLocal<Manager> sManager = new ThreadLocal<Manager>() {
@Override
protected Manager initialValue() {
return new Manager();
}
};
private Manager() {
}
public static Manager getInstance() {
return sManager.get();
}
}
參考
- 彻底理解ThreadLocal(http://blog.csdn.net/lufeng20/article/details/24314381)
另一鲜为人知的单例写法-ThreadLocal的更多相关文章
- Egret中的三种单例写法
1 普通的单例写法 as3中也是这么个写法. 缺点:每个单例类里都要写instance和getInstance. class Single{ private static instance:Singl ...
- Unity 单例写法
借鉴自:http://www.cnblogs.com/CodeCabin/p/unity_global_manager.html 实现复杂一些的全局控制,如切换游戏关卡等操作,更常用的方式是使用单例类 ...
- 设计模式课程 设计模式精讲 8-10 单例设计模式-ThreadLocal线程单例
1 课程讲解 1.1 应用场景 2 代码演练 2.1 threadLocal应用 1 课程讲解 1.1 应用场景 多线程的时候: 使用同步锁使用时间换空间的方式,(线程排队时间比较长) 而使用thre ...
- ARC模式下的单例写法
// 单例 + (id)sharedInstance { __strong static id sharedObject = nil; static dispatch_once_t onceToken ...
- swift3 单例写法
import UIKit class SingleOnce { // 单例 static let shared = SingleOnce.init() private init(){} // 其他方法 ...
- 基于单例使用ThreadLocal对多线程下数据的访问修改
package cn.lyy.thread; import java.util.Random; /** * 基于单例模式的基础上,使用ThreadLocal为每一个进入的线程生成一个实例, * 用来对 ...
- myapplication 单例写法
MyApplication extends Application private static MyApplication myApplication = null; oncreate中: @Ove ...
- C++单例写法
#define __xx(WaveClassFile::me()) class Xx : public QObject{ Q_OBJECT public: static Xx & me(); ...
- 十次艳遇单例设计模式(Singleton Pattern)
1.引言 单例设计模式(Singleton Pattern)是最简单且常见的设计模式之一,在它的核心结构中只包含一个被称为单例的特殊类.通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访 ...
随机推荐
- 不知道哪里alert undefined 用下面的语句是js报错.F12能提示报错的地方window.alert=function(aa){ if (typeof (aa)"undefined"){ throw "就是这";}};
不知道哪里alert undefined 用下面的语句是js报错.F12能提示报错的地方 var oldalert=window.alert; window.alert=function(aa){ i ...
- Centos7 搭建lnmp环境 (centos7+nginx+MySQL5.7.9+PHP7)
阿里云一台服务器出现问题! 我估计是一键安装包环境的原因,所以打算重新搭建下环境! 首先,当然是先做好快照!安全第一! 对系统盘做更换系统操作,装上纯净版的centos. 装好后,进入系统 一.挂载数 ...
- Linq-查询上一条下一条
//下一条 int pollid = poll.Where(f => f.PollID < CurrentId).OrderByDescending(o => o.PollID).F ...
- Java中动态代理方式:
JDK中生成代理对象的API 代理类所在包:java.lang.reflect.ProxyJDK实现代理只需要使用newProxyInstance方法,但是该方法需要接收三个参数,完整的写法是: st ...
- sql server2008R2 无法连接到WMI提供程序。你没有权限或者该服务器无法访问
在自己的Win8.1的系统在安装了Vs2013和Sqlserver2008R2 今天在打开ssms的时候发现连接不上数据库,且出现了以下问题 然后打开Sqlserver配置管理器准备看看sqlserv ...
- ubuntu16.04与mysql的运维注意事项
1:环境 ubuntu16.04 虚拟机,需要搭建一个MySQL的生产或者测试环境 2:操作步骤 2.1:更新系统源 首次给root用户指定密码 ,先用安装用户登录 sudo apt-get up ...
- CSOM中如何取到managed metadata类型字段的类型信息
Field.fieldTypeKind返回的是Invalid [解决方法] There is no "Metadata" type of field in the SP.Field ...
- 在linux 中wget 无法解析主机
vim /etc/resolv.cof 在里面加入节点 nameserver 8.8.8.8 / nameserver 8.8.4.4 即可 失败时: 成功时:
- vi入门到精通
VI是在Linux命令行下常用的文本编辑工具,在服务配置管理过程中经常用到:vi的常见的使用指南,互联网上随处可见,但仅能满足初学者对文档编辑的需求.这里就我自己在使用过程中通常用到的一些技巧操作方法 ...
- JavaScript 从闭包可以做什么开始,将有助于理解闭包
本文内容 函数内部访问全局变量 函数外部不能直接访问局部变量 函数外部访问局部变量 保护私有成员 持久性 模块化 抽象性 闭包是 JavaScript 的重要特性,非常强大,可用于执行复杂的计算,可并 ...