Javamex

Java discussion forum to accompany the Javamex web site.

I'm trying to sort out exactly how Java deals with the static portion of a class when it is loaded...

Is the class itself represented by an instance of Class?
Is there a "special" part of memory (static memory?) where static variables are stored?

I see a lot of conflicting opinions but few facts...

Thanks!

Views: 234

Reply to This

Replies to This Discussion

Hi Steve,

Probably the reason you see conflicting information is that some of what you're asking isn't set in stone.

Essentially, a VM must provide a means to "put/get a static field" (the PUTSTATIC and GETSTATIC bytecodes) and "invoke a static method" (INVOKESTATIC). There's really no obligation for the corresponding data or code to be stored in a particular place.

As well as normal fields, classes have a so-called "constant pool". In other words, there is a mechanism for javac to encode a final static (primitive or String) variable as a constant value. These constant values will very probably be stored in a "special place" by the JVM. But for non-final static fields and static methods, I imagine VMs would generally treat them as "normally as possible". (It doesn't make sense, for example, to have a special heap for statically-referenced objects, because they could be referred to by any instance variable at any given moment.)

Generally, a class is represented by an instance of Class, but at the same time, an instance of Class is treated as a "special type of object".

Hope that at least partially answers your question-- I know some of what I've said isn't very concrete, but that's because the exact internals really aren't very concretely defined.

Neil
Neil-

Thanks, that's basically what I expected to hear. I wanted to ask you specifically, because I trust your judgement. My question arose over a beginner's question about object and instance. That led to remarks about static variables, some of which I knew were not only incorrect but also misleading. I posted my own thoughts, and then I realized I was so certain, either.

After I posted here, I found a Sun document about choosing the right garbage collector. That document started with a fairly detailed discussion of the heap, which also clarified some things. Sun's VM seems to load class information, including methods and static variables, in a portion of the heap normally ignored by the garbage collector. That makes sense, classes and their static variables (not the values in those variables) typically don't change, so there is little reason for the garbage collector to examine them. That's the origin the "special memory" legend.

In addition, Class objects are certainly handled differently than objects composed of a class instance's variables, along with arrays, enums, and what not.

Again, thanks for the reply!

-Cordially, Steve

Reply to Discussion

RSS

© 2024   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service