Skip to content

Commit

Permalink
ThreadLocal参考案例,以及源码解析
Browse files Browse the repository at this point in the history
  • Loading branch information
googlemeoften committed Mar 28, 2016
1 parent 58773a3 commit 098c671
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package cn.edu.learn.interview.thread.communication;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
* @description: 使用threadLocal实现数据库的链接
* @author: hey
* @date 2016/3/28
* @version: 1.0
*/
public class ConnectionManager {
private static Log log = LogFactory.getLog(ConnectionManager.class);
private static ThreadLocal<Connection> connections = new ThreadLocal<Connection>() {
@Override
protected Connection initialValue() {
Connection con = null;

try {

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
log.debug("找不到驱动类");
}
return con;
}
};

public static Connection getConnection() {
return connections.get();
}

public void setConnection(Connection con) {
connections.set(con);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
ThreadLocal������
1��������˵��ÿ���̶߳�ά���ű����ĸ����������ұ������ֿ���ȥ����ThreadLocal��

�����ҿ���������뻹�Dz��ܹ����⣬��Ϊ��һֱȥѰ��ʹ��clone()�ĵط�������һֱû���ҵ�

�����ҷ��������ϵ��뷨���Լ�����������Դ�룬�������⵽ÿ���߳��ﱣ��Ķ�����clone�����ģ�

��ʵ����new�����Ķ���

2��Դ�������
ThreadLocal��get()������

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();
}
���Դ����Ҫ�漰������������

��һ�����õ���ǰ�̣߳����߳��л��һ��ThreadLocalMap�Ķ�����������������������ν�����ĵط�

�ڶ����������ֿ��ܣ�
1�����ThreadLocalMap����Ϊ���Ҹö����е�Ԫ�ز�Ϊ�գ��ʹӸö����л�ȡ���������ҷ���

2������Ϊ�գ�����setInitialValue����������ʼ��

ThreadLocal.setInitialValue����Դ��

private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
���Դ����Ҫ�漰����������

��һ��������initialValue()���������û�ó�ʼֵ���÷�������null�����ǿ�����д�÷�������������ConnectionManager���е����ӡ�

�ڶ�������ֵ���õ�map�У������ظ�ֵ

0 comments on commit 098c671

Please sign in to comment.