Your Question is not clear. You may not fully understand how Java Servlet technology works.
A Servlet is a class that is loaded upon first request by a client (web browser, etc.) or preloaded when servlet container starts. A thread is assigned to handle each incoming request to generate the outgoing response. Normally the servlet object does not stop running once started, until the servlet container closes. You must understand that a single servlet object servlets handles many request-response cycles by many users. See more discussion here.
A session is launched for each individual user’s set of request-response cycles. Each session is represented by a HttpSession object. Sessions automatically time-out if the user stops making requests. Implementations commonly default to a half-hour until time-out. You can adjust that default. This is probably the solution you are looking for, but I'm not sure given the lack of clarity in your question. Call setMaxInactiveInterval
on that session object.
int seconds = TimeUnit.MINUTES.toSeconds( 3 ) ; // Three minutes converted to a number of seconds.
someHttpSession.setMaxInactiveInterval( seconds );
Also, you can programmatically close a session by calling invalidate
on that session object, as discussed here.
You can ask for that session’s start time as a count of milliseconds since the epoch of 1970 UTC by calling getCreationTime
.
long millisSinceEpoch = someHttpSession.getCreationTime();
Make an Instant
from that to see that moment in UTC.
Instant instantSessionStarted = Instant.ofEpochMilli( millisSinceEpoch );
Use Duration
object to see elapsed time. For current moment, call Instant.now
.
Duration durationOfThisSession = Duration.between( instantSessionStarted , Instant.now() );