Java: When are instance methods loaded in memory? - java

I would like to know that if I have the following class.
class Example {
public static void method1() {}
public void method2() {}
public void method3() {}
}
Only 1 method is static and it should be the first thing to be loaded in the memory during runtime. But what about the instance methods? Are they loaded in the memory when an instance of this class is created? Or are they already loaded when the class is loaded initially.
What I am trying to understand is if it is a better approach to have all the functionality in the same class by having separate methods for each functionality or is it better to create a separate class for each functionality with only there respective methods in its class.
So will it help memory wise in the later case because I will only create the instance of the class that I need to use and only that much of methods will be loaded in the memory. Otherwise, in the former case, where I have 100 methods in the same class, but I only need to use just 2 methods out of them, it will be waste of memory because all 100 methods are loaded.
Any suggestions?

Actually memory allocation for class variables and class member functions/methods are done differently. When a class is being instantiated its class variables are being created in the memory which is call as data segment and method codes are created in code segment. IF we create ten objects of a particular class java virtual machine will create ten different code segments but only one code segment will be created for all the object. Java virtual machine will create a code segment only when there is at least one reference to that that class object in the code else it will not.
Code segment captured minimal memory only. It just stores assembly instructions created from code. Hence you no need to worry about it. For object also a programmer no need to worry about managing the memory in Java as there is a garbage collector in java.
Now answer to your question in my comment section:-
But will the methods themselves be stored somewhere in heap etc. ? So a class having 100 methods or 2 methods will behave the same memory wise?
As I said your method's codes will be converted into assembly instruction by your java virtual machine and will be stored in the memory in an instruction pointer for each method. Not necessarily now many method, it will depends on lines of code, recursion, loops, and condition etc. Yes if 100 methods of same size of codes with all the above then it will takes more memory than two methods.

Related

Where does static variables and methods are loaded in java?

I am little bit confused that where did static variables and methods are loaded. we say that static variables and methods are loaded in the static memory. bt public static void main() is loaded into stack .Since main() method is also static then how it is possible that main is loaded into stack.
and alse is static methods and variable are stored in different positions because we say that methods are loaded in different place in memory.
The stack is where things go when they are invoked/executed. It doesn't matter if it is static or not. Any running function goes onto the stack where it's local variables and all are held until the stack frame is popped.
For example, I can have main() call main() recursively over and over. Each one would be a new stack frame. The fact that it is a static function does not change that.
Static variables, on the other hand, are different. There will only be one instance of them and you know it explicitly. So, they can go into special storage and be treated differently (as are other global things like the class definitions and all that).
The actual implementation of this is not liable to be very useful, nor easily understandable. However, a model of it might help you understand the use of these things.
First of all, data and code are quite different animals in Java. Variables are going to have values that change at runtime; code never does that. So when you instantiate a class, you are never going to get another copy of the code.
Consider the class Class - instances of it exist, one per fully-qualified class in the program. I think of all code for one class, static or not, as being associated with its Class instance -- 'loaded' with it, if you prefer. Incidentally, and coincidentally, that's also where I think of its static variables being 'loaded'.
But the instance variables need multiple copies -- whenever you instantiate the class, you need another copy of them. So they are associated (or loaded) with the instance of the class when instantiated -- think of the pointer to the class as a pointer to a structure that contains all the instance variables of that class, plus a pointer to jump tables to its methods, etc.
I do not know what you mean by public static void main being "loaded onto the stack". Do you mean the code? Code never goes onto a stack per se. It wouldn't make any sense to have code from a (normal) class put on the stack, lost when the current method returns, and then have to load it again if the method were called.
I think there's part of your question I'm not getting to because I don't understand what you're asking.

Do java objects share method location in memory?

Consider this class:
public class Test {
private int bar = 5;
public void foo () {
System.out.println("hi");
}
}
Now imagine we have the following section of code executing:
Test obj1 = new Test();
Test obj2 = new Test();
Test obj3 = new Test();
All three objects exist in the same scope. Because bar is not static, there will be three separate instances of bar in memory.
Are there three instances of the method foo in memory?
Does the JVM do some magic so that each object can use one method declaration in memory?
Is there a name for this situation so that I can see if other languages do it?
Methods are referenced by indices, there are no instances of methods, i.e. they don't take up additional memory.
The Java instruction set responsible for handling a method based on a class is invokevirtual:
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.invokevirtual
Here is a more detailed look of what happens under the hood (explained far better then I could):
http://zeroturnaround.com/rebellabs/java-bytecode-fundamentals-using-objects-and-calling-methods/
Other references
How the hava virtual machine handles method invocation and return
Here is a similar SO question:
How much memory is used for function references in a Java object?
Are there three instances of the method foo in memory?
No.
Does the JVM do some magic so that each object can use one method declaration in memory?
No.
Is there a name for this situation so that I can see if other languages do it?
What makes you think there are any other languages that do it? The real question here is why do you think methods would be instantiated per instance? What would be the point?
To be clearer, there is absolutely no need for different objects to have different code for their methods. Assuming you have 3 instances of Test, you need three versions of the 'bar' member because they can have different values. However all of the three 'foo' methods do exactly the same thing. The bits that represent the code are absolutely identical. Having three (identical) versions would be completely pointless.
All other computer languages do this too. In fact you will find that on a computer, if you execute (say) a text editor on three documents at once, there will be three areas of data representing the three documents, but only one place in memory where the actual code of the application is stored. The three 'instances' share it.

Optimizing Java worker speed-wise

I've got a Java worker that handles a lot of data. It waits on a Redis queue in main() and then calls different functions to handle the data depending on type.
I've got two questions on optimizing the code:
Would it be better to have private static class variables and use them to send data to methods instead of using function arguments?
Would it speed up execution time if variables used in these often-called methods would be private static on class instead of declared always over again when entering the method?
Thanks
You are talking about speed, but static variables will help you mostly memory-wise.
If you are creating multiple instante variables (non-static fields) and thinking of changing to into a static one:
When multiple instances of a class need access to a particular object in a variable local to those instances (instance variable), it is better to make that variable a static variable rather than have each instance hold a separate reference. This reduces the space taken by each object (one less instance variable) and can also reduce the number of objects created if each instance creates a separate object to populate that instance variable. (Quoted from Java Performance Tuning book.)
If you are not creating instance variables, but just passing a variable along in parameters:
Performance-wise, there should be no difference. As a all method parameters in Java are passed value-by-reference, meaning that the actual variable is not copied over an over: only its address (pointer - a reference to the variable) is copied into the parameter of the called method.
In any case, static fields can compromise your code's readability (it can make them so much harder to maintain). If you really need a static behaviour, please also consider using a Singleton design pattern.
Bottom line is:
Seems to me your scenario is: You are just passing variables along (an not having instance variables).
I advise you to keep it that way. If you change it, there will be near-zero (if any) performance gain by using static fields -- on the other hand, your code will be much harder to maintain/understand/debug.

What is the main difference in object creation between Java and C++?

I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?"
I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when constructor of one class calls a method of another class which isn't constructed yet and so on, but I can't find anything obvious. The answer is supposed to be one or two sentences, so I don't think that description of whole object creation process in Java is what they had in mind.
Any ideas?
What is the main difference in object creation between Java and C++?
Unlike Java, in C++ objects can also be created on the stack.
For example in C++ you can write
Class obj; //object created on the stack
In Java you can write
Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object
In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):
In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)
What?
Let's imagine a Base class, with a virtual method foo().
Let's imagine a Derived class, inheriting from Base, who overrides the method foo()
The difference between C++ and Java is:
In Java, calling foo() from the Base class constructor will call Derived.foo()
In C++, calling foo() from the Base class constructor will call Base.foo()
Why?
The "bugs" for each languages are different:
In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.
Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.
Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml
In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.
During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.
Scott Meyers, http://www.artima.com/cppsource/nevercall.html
Besides heap/stack issues I'd say: C++ constructors have initialization lists while Java uses assignment. See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for details.
I would answer: C++ allows creating an object everywhere: on the heap, stack, member. Java forces you allocate objects on the heap, always.
In Java, the Java Virtual Machine (JVM) that executes Java code has to might1 log all objects being created (or references to them to be exact) so that the memory allocated for them can later be freed automatically by garbage collection when objects are not referenced any more.
EDIT: I'm not sure whether this can be attributed to object creation in the strict sense but it surely happens somewhen between creation and assignment to a variable, even without an explicit assignment (when you create an object without assigning it, the JVM has to auto-release it some time after that as there are no more references).
In C++, only objects created on the stack are released automatically (when they get out of scope) unless you use some mechanism that handles this for you.
1: Depending on the JVM's implementation.
There is one main design difference between constructors in C++ and Java. Other differences follow from this design decision.
The main difference is that the JVM first initializes all members to zero, before starting to execute any constructor. In C++, member initialization is part of the constructor.
The result is that during execution of a base class constructor, in C++ the members of the derived class haven't been initialized yet! In Java, they have been zero-initialized.
Hence the rule, which is explained in paercebal's answer, that virtual calls called from a constructor cannot descend into a derived class. Otherwise uninitialized members could be accessed.
Assuming that c++ uses alloc() when the new call is made, then that might be what they are
looking for. (I do not know C++, so here I can be very wrong)
Java's memory model allocates a chunk of memory when it needs it, and for each new it uses of
this pre-allocated area. This means that a new in java is just setting a pointer to a
memory segment and moving the free pointer while a new in C++ (granted it uses malloc in the background)
will result in a system call.
This makes objects cheaper to create in Java than languages using malloc;
at least when there is no initialization ocuring.
In short - creating objects in Java is cheap - don't worry about it unless you create loads of them.

Does having more methods in a class mean that object uses more memory at runtime

Say I have one class ClassBig with 100 methods inside, and a second with only 10 methods ClassSmall
When I have objects at runtime
ClassBig big = new ClassBig();
ClassSmall small = new ClassSmall();
Does the larger class take up more memory space?
If both classes contained an identical method, does the larger class take longer to execute it?
The in-memory representation of an instance of a class is mainly just its internal state plus a pointer to an in-memory representation of the class itself. The internal representation of an instance method has one more argument than you specified in the class definition - the implicit this reference. This is how we can store only one copy of the instance method, rather than a new copy for every instance.
So a class with more methods will take up more memory than a class with less methods (the code has to go somewhere), but an instance of a class with more methods will use the same amount of memory, assuming the classes have the same data members.
Execution time will not be affected by the number of other methods in the class.

Categories

Resources