Previously, we introduced that iosessionrecycler is an interface used to recycle sessions that are no longer in use. expiringsessionrecycler is an implementation class used to recycle sessions with expired timeout.
Private expiringmap <object, iosession> sessionmap; // session set to be processed
Private expiringmap <object, iosession>. expirer mapexpirer; // recycles
The sessionmap key is composed of the local address and the remote address. The value is the session corresponding to the two addresses.
The expirer class implements the runnable interface. This thread monitors expiringmap and removes elements that exceed the threshold value in expiringmap from expiringmap. This thread calls setdaemon (true) and runs in the background as a daemon. The specific process is as follows:
Private void processexpires ()
{
Long timenow = system. currenttimemillis (); // current time
For (expiringobject O: Delegate. Values ())
{
If (timetolivemillis <= 0)
{
Continue;
}
Long timeidle = timenow-o. getlastaccesstime (); // Time Difference
If (timeidle> = timetolivemillis)
{// Timeout
Delegate. Remove (O. getkey ());
For (expirationlistener <v> listener: expirationlisteners)
{// Call listener
Listener. Expired (O. getvalue ());
}
}
}
}
The lock mechanism is required to start/Close the timeout check thread. Here the read/write lock is used:
Private Final readwritelock statelock = new reentrantreadwritelock ();
Public void startexpiring ()
{
Statelock. writelock (). Lock ();
Try
{
If (! Running)
{
Running = true;
Expirerthread. Start ();
}
}
Finally
{
Statelock. writelock (). Unlock ();
}
}
Public void stopexpiring ()
{
Statelock. writelock (). Lock ();
Try
{
If (running)
{
Running = false;
Expirerthread. Interrupt ();
}
}
Finally
{
Statelock. writelock (). Unlock ();
}
}
Session Timeout listener:
Private class defaultexpirationlistener implements
Expirationlistener <iosession> {
Public void expired (iosession expiredsession ){
Expiredsession. Close (); // close the timeout session
}
}
Author: phinecos)
Source: http://phinecos.cnblogs.com/
The copyright of this article is shared by the author and the blog Park. You are welcome to repost it, but please keep this statement and provide the original article connection clearly on the article page.
Author: Dongting sangren
Source: http://phinecos.cnblogs.com/
This blog complies with the Creative Commons Attribution 3.0 License. If it is used for non-commercial purposes, you can reprint it freely, but please keep the original author information and article URL.