Hi, What happens when we call a method in a class, I wanted to know how JVM deals with this..Like will it take only the definition of the method place it separately in the memory and start executing it...how it happens?.. Is there any other way... If that function is called at a time by more than one object , then what?
There is a nice distinction between code and data. The JVM is smart enough to only load the code once. If you make a hundred instances of String and start invoking methods, the JVM uses the same copy of the code every time. The JVM has some leeway in when it loads classes (the code) but it's usually safe to assume they are loaded the first time you reference them, though "reference" can be a bit tricky. Data has to be different. When you create an instance, the JVM sets aside memory for all the member variables so the instance can work with its own set of data. That's really what makes an instance interesting. I left out static variables to make that last paragraph simple. Static variables follow a different rule. There is one copy of a static variable per class, not per instance. The JVM sets aside space the first time the class is referenced and all references to the static variables work with the same copy. This kind of stuff is exactly what trips up a lot of people who are new to OO languages. I work in a shop where people move from COBOL to OO languages, and they haven't had much hands on dealing with dynamic memory allocation. So if this seems strange to you, you're in good company. If it all clicks and sounds perfectly sensible, you're ready to roll!
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Jan 29, 2003
D'oh! You asked one more question - What if two instances run the same method at the same time? Now we're into the whole threading world. Each thread works through the method independently. Way down in the JVM it keeps a next instruction pointer. It executes one instruction, then fetches and executes the next. So two threads with their own pointers can walk through the same code at the same time. What if two threads are working on the same static variable? You can surely have trouble! The "synchronized" keyword is the heart of the solution. It's way too big a topic for me, but there are great tutorials and books around. Have any links, readers?