Object methods stored in stack or heap? - memory-management

What happens to the methods inside the objects of the heap?
So I have been reading about stack and heap memory management.
Methods and variables(inside methods) are stored in the stack.
Objects and Instance variables are stored inside the heap.
When an object is called inside a stack method it has a pointer to the heap object.
I would assume these methods are stored on the stack, because 'methods are stored on the stack'. But I am unable to find confirmation about this. What happens to for example the constructor?
Articles or tutorial video's I have seen only give examples of methods in the main class.
Anyone able to answer this question?

Will explain based on how it works in Java.
Methods and variables(inside methods) are stored in the stack.
Local variables (variables inside methods) are stored in the stack. But not the method itself.
By method, we refer to the behaviour or the list of instructions that needs to be executed. This does not vary every method call and not even vary for every object instance created. The behaviour remains the same at the class level.
The behaviour is stored in a region called Method area. You can refer Java Spec for more details.
As per spec,
The method area is created on virtual machine start-up. Although the method area is logically part of the heap, simple implementations may choose not to either garbage collect or compact it. This version of the Java Virtual Machine specification does not mandate the location of the method area or the policies used to manage compiled code.
It is left to the JVM implementation on where the method area is located.
Implementations like HotSpot VM, until Java 7, used to store the method area as part of the heap. But from Java 8, it is moved out of heap and the space allocated for heap is not consumed by the method area.
What happens to for example the constructor?
Constructions are methods with a special name called, <init>.1. They are stored in the same way as other methods.
As a side note, there is a class initialization method, called <clint>, which handles static block in class.2

Related

ColdFusion memory usage for Components

I am creating a site using VMC and using beans to transfer the data from the Model to the Controller/Views.
I plan to implement some basic and very simple caching that will store the beans in a simple struct if they have not changed (as usage grows, we will implement a better caching system around ver 1.3).
So the question goes to what goes in our bean.
One type of bean would only hold the basic data and would rely on some outside service to do the rest of the work (contacting the DAO to get the query, parsing the query to load the bean values). This is the "anemic bean" model as I have been told repeatedly by a co-worker :-).
Another type of bean would be more self-contained. It would know where the DAO is so would call the DAO directly to get the data query. It would contain necessary functions to parse out the query and set the properties. It would basically combine much of the "service" layer with the bean, leaving the direct database in the DAO layer.
Of course, to the controller/views, both beans would look and act the same.
But the question is memory and how ColdFusion/Java deals with it.
With the anemic model, the bean would just have enough memory to hold the property variables with just a touch more to let it point to the Service when it needs to.
With the heavier functions in the second type bean, would it take up more memory in the cache??? Would each copy of the bean have a full copy of the methods?
I tend to think that the second model would not have much more memory since they would "share" the methods and would only need memory for the property variables.
IMHO the second method would simplify the codebase, since the code the bean needs would be closer to the bean rather than scattered between the DAO and Services. And it would reduce simple functions in the Service that merely pass along calls to the DAO of the bean could go directly to the DAO when it needed it...
Does the question make sense?? Or at least how I am asking it?
All the memory management is handed at Java level, so it follows the same rules. In Java the only "new" memory that's allocated when an object instance is created is for its member variables; there is not memory foot print for the methods of the component/class itself: that stuff is only stored in memory once, with a reference back to it.
One possible consideration is that each method of a CFC is compiled as its own discrete class (why? I don't know), so each method is its own class. This will perhaps mean a slightly larger memory footprint for CFC usage compared to Java class usage, but this will still not be something that scales with object-instantiation: each instance of an object will still just consume memory for its member variables, not the methods of the CFC that defines the object.
all cfm pages are compiled to memory by default, a CFC needs to implicitly be stored in memory (application scope for example) in order to avoid instantiating it each time, however you do it requires the same memory for the same component, any additional usage will depend on any data you are storing within your component or bean.
Have you had a look at ColdSpring ?

Check Value of .NET Handle ^

Here's my situation:
I have .NET wrapper-objects in a C++/CLI layer that hold pointers to unmanaged C++ objects. I've implemented the finalizer so that it deletes the unmanaged memory pointed to by the wrapper-object on garbage-collection and sets the pointer to null.
Here's the problem:
I'm watching the finalizer for the .NET wrapper-object and it gets called twice and tries to delete the same memory twice, indicating that I have somehow created 2 .NET wrapper objects that go out-of-scope, and are garbage collected while I'm still expecting the wrapper object to be in scope (these wrapper objects are getting passed to a VB.NET application).
Here's my question:
Is there anyway for me to check the handle value so that I can confirm where the wrapper objects are getting created (copied or whatever)? Currently I'm looking at the handle values (EG - 0x0014fe80), but I see 3 different values for when the object is created, added to a collection, and deleted. So I'm not sure if the GC is just moving stuff around and this is the same object, or if I'm actually seeing 3 different objects that reference the same unmanaged memory. I would like to resolve the duplicate object copies if possible, but I understand that I will probably want to implement some sort of smart pointer so that this doesn't happen.
Thanks,
Ian
Take a look at this question
Here is an implementation of a scoped_ptr that is noncopyable and has an auto-release mechanism for unmanaged objects, by #Ben Voigt
Yeah, I ended up modifying an auto_ptr class to be a shared pointer to ensure that the unmanaged memory is only deleted once through the smart pointer finalizer. I'm assuming I did something similar to all the other implementations; I created a static dictionary in the auto_ptr template class, using the native pointer value as the key, that is checked every time the finalizer is called to update the count of each item, or delete the memory.

VB6 Is it possible to implement the Singleton design pattern?

Within VB6 is it possible to implement the Singleton design pattern?
Currently the legacy system I work on has a large about of IO performed by multiple instances of a particular class. It is desirable to clean up all these instances and have the IO performed by one instance only. This would allow us to add meaningful logging and monitoring to the IO routines.
There are so many ways to do this, and it depends if this is a multi-project application with different dlls or a single project.
If it is single project and there is a large amount of code that you are worrying about chaning/breaking then I suggest the following:
Given a class clsIOProvider that is instantiated all over the place, create a module modIOProvider in the same project.
For each method / property defined in clsIOProvider, create the same set of methods in modIOProvider.
The implementation of those methods, as well as the instance data of the class, should be cloned from clsIOProvider to modIOProvider.
All methods and properties in clsIOProvider should be chnaged to forward to the implementation in modIOProvider. The class should no longer have an instance data.
(Optional) If the class requires the use of the constructor and destructor (Initialize/Terminate), forward those to modIOProvider as well. Add a single instnace counter within modIOProvider to track the number of instances. Run your initialzation code when the instance counter goes from 0 to 1, and your termination code when the instance counter goes from 1 to 0.
The advantage of this is that you do not have to change the coe in the scores of places that are utilizeing the clsIOProvider class. They are happily unaware that the object is now effectively a singleton.
If coding a proejct from scratch I would do this a bit differently, but as a refactoring appraoch wahat I've outlined should work well.
It's easy enough to only create and use one instance of an object. How you do it depends on your code what it does and where it's called from.
In one process, you can just have a single variable in a global module with an instance, maybe with a factory function that creates it on first use.
If it's shared by multiple process, it complicates things, but can be done with an ActiveX EXE and the Running Object Table.

Difference between local and instance variables in ruby

I am working on a script that creates several fairly complex nested hash datastructures and then iterates through them conditionally creating database records. This is a standalone script using active record. After several minutes of running I noticed a significant lag in server responsiveness and discovered that the script, while being set to be nice +19, was enjoying a steady %85 - %90 total server memory.
In this case I am using instance variables simply for readability. It helps knowing what is going to be re-used outside of the loop vs. what won't. Is there a reason to not use instance variables when they are not needed? Are there differences in memory allocation and management between local and instance variables? Would it help setting #variable = nil when its no longer needed?
An instance variable continues to exist for the life of the object that holds it. A local variable exists only within a single method, block or module body.
If you're assuming objects in your object's instance variables will be garbage-collected just because you don't intend to refer to them in the future, that isn't how it works. The garbage collector only knows whether there's a reachable reference to the object — and there is if it's in an instance variable.
Setting #variable = nil destroys the reference to the object that the instance variable once pointed to. When there are no more remaining references to an object, it should be collected by the garbage collector eventually. I say "eventually" because the GC is somewhat unpredictable. However, it's easy to have a memory leak by a "dangling reference" and possibly (depending on how the GC is implemented) circular references. What else refers to this object?

Object address in Ruby

Short version: The default inspect method for a class displays the object's address.* How can I do this in a custom inspect method of my own?
*(To be clear, I want the 8-digit hex number you would normally get from inspect. I don't care about the actual memory address. I'm just calling it a memory address because it looks like one. I know Ruby is memory-safe.)
Long version: I have two classes, Thing and ThingList. ThingList is a subclass of Array specifically designed to hold Things. Due to the nature of Things and the way they are used in my program, Things have an instance variable #container that points back to the ThingList that holds the Thing.
It is possible for two Things to have exactly the same data. Therefore, when I'm debugging the application, the only way I can reliably differentiate between two Things is to use inspect, which displays their address. When I inspect a Thing, however, I get pages upon pages of output because inspect will recursively inspect #container, causing every Thing in the list to be inspected as well!
All I need is the first part of that output. How can I write a custom inspect method on Thing that will just display this?
#<Thing:0xb7727704>
EDIT: I just realized that the default to_s does exactly this. I didn't notice this earlier because I have a custom to_s that provides human-readable details about the object.
Assume that I cannot use to_s, and that I must write a custom inspect.
You can get the address using object_id and multiplying it by 2* and display it in hex using sprintf (aka %):
"#<Thing:0x%08x>" % (object_id * 2)
Of course, as long as you only need the number to be unique and don't care that it's the actual address, you can just leave out the * 2.
* For reasons that you don't need to understand (meaning: I don't understand them), object_id returns half the object's memory address, so you need to multiply by 2 to get the actual address.
This is impossible. There is no way in Ruby to get the memory address of an object, since Ruby is a memory-safe language which has (by design) no methods for accessing memory directly. In fact, in many implementations of Ruby, objects don't even have a memory address. And in most of the implementations that do map objects directly to memory, the memory address potentially changes after every garbage collection.
The reason why using the memory address as an identifier in current versions of MRI and YARV accidentally works, is because they have a crappy garbage collector implementation that never defragments memory. All other implementations have garbage collectors which do defragment memory, and thus move objects around in memory, thereby changing their address.
If you tie your implementation to the memory address, your code will only ever work on slow implementations with crappy garbage collectors. And it isn't even guaranteed that MRI and YARV will always have crappy garbage collectors, in fact, in both implementations the garbage collector has been identified as one of the major performance bottlenecks and it is safe to assume that there will be changes to the garbage collectors. There are already some major changes to YARV's garbage collector in the SVN, which will be part of YARV 1.9.3 and YARV 2.0.
If you want an ID for objects, use Object#object_id.
Instead of subclassing Array your class instances could delegate to one for the desired methods so that you don't inherit the overridden inspect method.

Resources