Skip to content

Instantly share code, notes, and snippets.

@chanjarster
Created January 26, 2015 03:08
Show Gist options
  • Save chanjarster/e1793251477cbabfbe92 to your computer and use it in GitHub Desktop.
Save chanjarster/e1793251477cbabfbe92 to your computer and use it in GitHub Desktop.
多线程访问到过期Session的测试代码
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.session.StandardManager;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
*
* 1. 新建一个maven项目
* 2. 在pom.xml里添加以下依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>7.0.57</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-juli</artifactId>
<version>7.0.57</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>7.0.57</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<version>7.0.57</version>
</dependency>
* 3. 运行这个程序
* 4. 然后访问 http://localhost:8080/
* 5. 等待一会儿看控制台输出,会有IllegateStateException抛出
*
*/
public class AccessSessionInAnotherThread {
public static void main(String[] args) throws LifecycleException, ServletException {
Tomcat tomcat = new Tomcat();
tomcat.getHost().setBackgroundProcessorDelay(1);
tomcat.setPort(8080);
Context rootCtx = tomcat.addContext("/", "/");
tomcat.addServlet("/", "default", new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final HttpSession session = req.getSession();
session.setAttribute("abc", "fsfsdfsdfsdf");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
// 2秒后再尝试访问session
// attempt to access session after 2 seconds
Thread.sleep(2000l);
session.getAttribute("abc");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
resp.getWriter().println("DefaultServlet");
}
});
rootCtx.addServletMapping("/", "default");
tomcat.start();
// 设置默认的session 最大非激活间隔时长1秒
// set session max inactive interval to 1 second
rootCtx.getManager().setMaxInactiveInterval(1);
// 设置manager的清理频率,默认是6,这里改成1
// set session expiring frequence to 1
((StandardManager)rootCtx.getManager()).setProcessExpiresFrequency(1);
tomcat.getServer().await();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment