When using hibernate to develop DAO module, we have the most dealings with session, so how to manage the session reasonably and avoid the frequent creation and destruction of session is very important to improve the performance of the system. It used to be done automatically through Eclipse Plug-ins, and of course the effect was good, but it was always uncomfortable (not reading those lengthy code), so now you want to implement the session Management code yourself.
We know that the session is created by Sessionfactory, and the implementation of Sessionfactory is thread-safe, and multiple concurrent threads can access a sessionfactory and get the session instance from it. So is the session thread-safe? I'm sorry, the answer is in the negative. The session contains state information about the operation of the database, so if multiple threads are using a session instance for CRUD at the same time, it is very likely that the data access will be confusing, can you imagine the situation where the thread that you can't predict the execution order will operate on one of your records?
In the many management scenarios of the session, we are today to recognize a solution called threadlocal mode.
As early as Java1.2 was launched, a new support was introduced in the Java platform: java.lang.ThreadLocal, which provided us with a new option for multithreaded programming. What is threadlocal? In fact, Threadlocal is not a local implementation version of a thread, it's not a threads, it's thread local variable. Perhaps it would be more appropriate to name it Threadlocalvar. A thread-local variable (ThreadLocal) is very simple in that it provides a copy of the variable value for each thread that uses a variable, and each thread can independently alter its own copy without conflict with the replica of the other thread. From a thread's point of view, it's as if every thread has exactly one of these variables.
How does threadlocal maintain a copy of a variable for each thread? In fact, the idea of implementation is very simple, in the Threadlocal class has a map, used to store a copy of each thread's variables. For example, the following sample implementation (for simplicity, does not consider the generics of the collection):
public class ThreadLocal {
private Map values = Collections.synchronizedMap(new HashMap());
public Object get() {
Thread currentThread = Thread.currentThread();
Object result = values.get(currentThread);
if(result == null&&!values.containsKey(currentThread)) {
result = initialValue();
values.put(currentThread, result);
}
return result;
}
public void set(Object newValue) {
values.put(Thread.currentThread(), newValue);
}
public Object initialValue() {
return null;
}
}