4

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?

Dustin Sun
  • 5,292
  • 9
  • 49
  • 87

2 Answers2

6

In the simple case, you can assume that multiple instances of Student will share the same static nextID field. However, one should think beyond the simple case (or document that you haven't). In this case, it's fine unless the instance id fields derived from the nextID counter 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()....

Community
  • 1
  • 1
andersoj
  • 22,406
  • 7
  • 62
  • 73
  • Clarification: *loaded by different classloaders* - if sessions are spread out among different JVMs it is almost assuredly the case that the static data will *not* be shared as expected (I wouldn't be surprised to find some specialty distributed cache/classloader counter-example...). –  Nov 01 '10 at 19:12
0

It depends on your application container and the configuration.

A static member will be the same for all sessions running within a JVM instance, but your configuration may be creating multiple instances.

If you want to keep this consistent and portable, you should not rely on it being the same across all sessions. This can also allow you to scale to multiple machines if needed without changing this code.

Alan Geleynse
  • 24,821
  • 5
  • 46
  • 55
  • 1
    -1 not true; `static` instances are per classloader, not per application/JVM – sleske Nov 01 '10 at 18:56
  • Ah good point, that's what I had meant but typed the wrong thing. Thanks for the correction, looks like someone else had an answer with that. – Alan Geleynse Nov 01 '10 at 18:57