I am developing a web application using Java/JSP.
One class, say Student, has a static member
static private int _nextID;
I want to know, if this _nextID is the same among all user sessions? Or each session has its own _nextID?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In the simple case, you can assume that multiple instances of
Studentwill share the same staticnextIDfield. However, one should think beyond the simple case (or document that you haven’t). In this case, it’s fine unless the instanceidfields derived from thenextIDcounter propagate out into a larger application where the IDs are meant to be unique. In that case, you want a more robust ID generator (maybe you want a UUID; maybe you want a primary key in a database; maybe something else).Ask yourself carefully what the required scope of the unique IDs is. Then seek a solution that solves that problem and document it in the class.
In general, static fields within the same-named class, but loaded by different classloaders (in the same or in different JVMs) may be different instances, something people most often notice when trying to implement the Singleton pattern. So the scope of your static variable depends (in complicated cases) on the relevant classloaders. Some more (recent) detail about Java namespaces defined by classloader is here and here.
Related on SO: Difference between
Thread.getContextClassLoader()….