Reputation: 4432
If I have static class, how does jvm guarantee it is initialized once? What happens when two threads simultaneously try to access this first time? Is this feature language invariant? EDIT : It is about a class which has static variables.
Upvotes: 0
Views: 2323
Reputation: 21795
The JVM guarantees that ANY class is initialised exactly once.
What exact low-level mechanism is uses to do this is really JVM-specific, but the thing you need to know as a programmer is that it IS thread-safe per se to attempt to access/initialise the same class from different threads. (Of course, that just goes for class-loading: in terms of accessing any immutable data, be it static or of a particular instance, you need to take appropriate measures.)
Upvotes: 2
Reputation: 35598
Static anything is initialized when the class is loaded, not when the first thread attempts to access it. However, static
for a class is not the same as static
for a data member or function/method. See this article for more information about that. If you are asking about data members, if they are static, then they are considered to be "class variables" or "class methods" not "object variables" (see this article from Oracle for that discussion). It accomplishes that by making them part of the class object itself rather than the instances. There is only ever one class object for any given class.
With regards to your question about other languages: no, static can mean many different things depending on the language.
Upvotes: 0
Reputation: 8727
First off, the static keyword is not that commonly used in class declarations, although it can be used there, but means something different than it does for variables or methods.
Did you really want to know about static classes? Or was it a question about static variables/methods?
Upvotes: 0
Reputation: 533432
You can have a static nested class and the behaves like any other class.
I assume you are referring to static code/blocks and class initialisation. The JVM guarantees that a class will be loaded by only one thread. Since its builtin to the JVM I don't imagine any languages wouldn't use it.
Upvotes: 1