When do variable values die or deleted in Java
I thought I already know when a variable has a value. But I was surprised that the variable already have a value when I open it in another browser. I guess that the value is still reside in the web server. I was thinking that when I open it to another browser even to another computer it will have its own variable located in memory.
I declare the variable set to null on it first occurrence in a global scope in my Servlets.
List<RecordsInfo> recordsInfo = null;
//with getter and setter;
then I have a function like this
function exportToExcel(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String filePath = "";
try {
if(recordsInfo != null){
/*I need to check first if recordsInfo has already value before creating an excel file.
This is to make sure that the records viewed are the same and will not make another query.*/
filePath = excelExporter.generateExcel(recordsInfo); //do something...
request.setAttribute("filePath ",filePath );
getServletContext().getRequestDispatcher("/docs/download.jsp").forward(request, response);
} else {
//so something....
}
} catch (Exception e)
e.printStackTrace();
}
}
download.jsp (JSTL)
Click <a href="${filePath}">here</a> to download.
I know I can get the value of recordsInfo after I initialized it, so I used it in exportToExcel. But my problem is other browser that use the same function get the same result, which I thought it is null because it have different session.
Although I already have plan to fixed this, I just want to have some advise from the expert.
My question is when do variable die (when Java garbage collector disposed it) and what is the best practice to declare a variable that is unique for every sess开发者_开发技巧ion. I hope I made my question clear. I'll appreciate any help. Thanks!
I declare the variable set to null on it first occurrence in a global scope in my Servlets.
Servlet is loaded once into memory when it is requested first..
Now for each request its service method will get called. but you have recordsInfo
at the global scope so it would be shared for all the session/request until the servlet is reloaded by class loaders.
So for your scenario , you can set recordsInfo
as session attribute as you need it different for different session
and to be cached for requests
Update for your new Q.:
In which memory the Servlet will load, is it in web-server?
Memory will be your machine's memory, particularly heap memory of your jvm on which server is running.
yes if its too big to cache, don't
精彩评论