Memory, instance vs static methods?

Well, have memory problems again.
Question: what is more efficient: using one single instance of a class all over the place, or put static methods in this class, so no instance is needed. I'm guessing it doesn't make a lot of difference, but who knows, I could be wrong...

Well, it appears that they don't affect runtime memory as long as the class is not needed. I guess the classloader will only load the class onto the heap from jar.
The application start about 100 KB of memory is available (and that is about all of the heap). While creating more objects, memory usage increases drasticly. Definantly more than only the data stored in the classes, so it must also be loading the bytecode at that time.
I still have some tricks up my sleeve, so I hope I can work it out...

Similar Messages

  • Memory management with static methods

    I made a class with no attributes and only static methods with the purpose of maintaining as little as possible about it in memory. What information is kept in memory by the JVM about such a class ?
    Thanx in advance :)

    Static methods don't consume less memory than regular instance
    methods. Well, not exactly: a regular method requires a reference
    to an instance as a hidden additional parameter. Thus, specifying
    static for methods that don't access the object may actually save
    a few bytes. However, the code is not duplicated for each instance.
    Additionally, the JVM must keep any initialization values and the
    names of the class and the methods, as needed by reflection.
    Given suitable debugging options, local variables names and line
    number may be kept in memory as well. Finally, all hosekeeping
    info (gc, references and the like) must be kept in memory.

  • Are DLL methods called as instance or static methods from Java ?

    Hi,
    I have only a small question.
    When I call a C++ DLL method from Java using JNI, do I instantiate it like an object method or is it called as a static method ?
    I am asking you this because I will use servlets (Java 1.2.2) to call a DLL. These servlets may run concurrently in any moment, and I pass some data to this DLL. I want to know if there is any possibility of this data becoming corrupt, because of one concurrent servlet rewriting the data another servlet has passed.
    Thanks and regards.

    The question is not specific enough.
    Methods in C/C++ can be qualified with the following forms:
    -global (C/C++)
    -static member(C++ class method)
    -instance member(C++ class method)
    Since you didn't provide your code I couldn't possible determine which of the above you are using, but presumably you know.
    On the other hand a java native method is either static or non-static depending on how you defined it in the class. Once again without the code there is no way to say and presumably you already know this.
    The context of the methods is the same context that a similar servlet method has. But naturally in C/C++ is is easy to circumvent the context - for example by using a global variable.
    Data in C/C++ can always become corrupt and in the vast (all?) cases it is because something is wrong in the C/C++ code. Like a pointer that is not initialized, or a pointer used after it is free'd. Or writing past the end of a buffer, or writing before the beginning of a buffer.

  • Static methods, what for?

    What are static methods for? is there something that is not possible through methods associated with instances (non-static methods) ?

    There are many examples of static mehods in the Java API. For example the Math or the System class. All methods in this classes are static. So you dont have to instantiate the system class. In fact it is even not possible to instantiate the System class. System is final and all Constructors are private.
    Another use for static methods is the access to private static variables.

  • Static method and threads?

    I have a question regarding "static". for example, I have the following code
    class Test{
    public int i=0;
    public static calculateInt(){
    ....some operations on i;
    if two processes attempt to call Test.calculateInt() at the same time. What will the effects be? shall these two calls be implemented totally independent? each call holds it own "i" for calculation. OR there will be operation conflicit on i.
    what if I change "public i" to :private i", the same effects?

    You can't operate on i in a static method, since i is an instance variable.
    If you make i static, then you can operate on it in a static method. In that case, all threads will share a single i--there's only one i for the whole class, and threads don't change that. Making it private won't change that.
    If you make the method into an instance (non-static) method, then any threads operating on the same instance will share the same i, regardless of whether it's public or private. Different threads operating on different instances will each have their own i.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Also check out http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

  • Static method decisions

    Dear all experts,
    I have got some problems understanding when to use static methods or passing the classes through constructor.
    I have got a class which needs to be accessed by several classes and also the classes inside the classes etc....
    Instead of passing classes around, should I just create a single static class which can be accessed by all the classes without needing to instantiate the class?
    I found that, i particularly in doubt when there are classes like "TableParser", "PropertiesReader" etc which some classes deep down in the hierarchy need access to those classes...
    Also, making the class static would it decrease the security of the whole program?? Say if i have got an encrytion class which does all the encrypt and decrypt, if i let it be static, isn't it easier to let people accessing the method? the same applies to properties editor etc??
    Any help would be really appreciated.
    Thx

    thx again jverd... (remember the security question? :)
    )I remember your id, but I didn't recall which thread(s) I had seen it in.
    >
    based on the understanding of what you said, do you
    mean that, if i am only using a class to store or read
    a setting file, it's ok to let it static? (so that all
    classes can access it whenever they like without
    passing the parser class to classes?)Um, again, you're terminology's a little off, so I'm not sure exactly what you mean, and even the description "store or read a seting file" could have a couple of interpretations.
    For example....You read the file once, and the config data it constains is accessible throughout your app and never changes. This might be a candidate for a class that only had static methods, but it would be kind of inflexible. What if later some other part of your app, or some other library that you develop that your app is going to use, wants to get its configuration from a file. In that case, I might want to have a couple instances of that class around. One for the global config that reads one file, and another for the config for that library that might read another file.
    I'd probably not even think about it as "reading a settings file." Rather, I'd see that as two parts: providing config settings to the app via a class, and reading a file to populate that class. The settings would exist independent of the fact that you can populate them from a file.
    I'd think about how I want to use them and decide whether to instantiate the class or use static methods based on that. Separately, I'd think about how this class or an instance of it is gonna get popuated with data from outside the program.
    I might decide to have different instances hold different sets of config data, and therefore use instance (non-static) methods to access the data in each of those instances, but I might register the instances--say by name, or maybe just in a list--and I could use a static method to acess the map or list: Config dbConfig = Config.getConfig("database"); Also, I wouldn't generally make a decsision on whether to use class methods or instance methods based on not having to pass a parameter.
    If you're thinking "I'd like to use static because it's easier. Can I get away with it here," then you're viewing objects as a burden to be avoided, which kind of defeats the purpose of using OO techniques in the first place.

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

  • Static method - memory usage

    will an application containing many static methods use more memory than an application w/ less static methods? are there any performance or memory issues w/ using static methods?

    I totally disagree that one should let oop principles NOT performance dominate design. While you may have a point in 99.99% of applications, I am in the 0.01% where performance has forced me to implement some hard choices.
    If static is faster and you call that method millions of time you may have some real issues to face. Let's say you lose a microsecond on each call by going non-static. That means for 1x10^6 calls you've lost a second. Which may not seem like a lot, but in multi-threaded user apps such as servers, this is very significant.
    I'd argue that there shouldn't even be a method. In fact just expose the instance variables and access the data directly, or don't even have the class and just in-line. Or even better, jni. How about just write it in Assembler. Where to draw the line???
    Before rants occur, this is only important to do in critical sections of code. Not recommended where you can use well structured oop principles which are preferred.

  • From Classic abap FMs to ObjectOriented instance/static methods: reference

    Hi All,
    we are migrating one of our project developed using classic abap to abap objects.
    mostly we are replacing the Function modules with either instance methods or static methods.
    for e.g.
    if there are FMs like GUI_UPLOAD, SO_NEW_DOCUMENT_SEND_API1 are used, after exploring in sdn for abap objects, we realized
    we can use cl_gui_frontend_services=>gui_upload( ) instead of the GUI_UPLOAD.
    send_request = cl_bcs=>create_persistent( ). send_request->send( ).  can be used instead of SO_NEW_DOCUMENT_SEND_API1
    like that there are several FMs present, is there any easy way where we can find this reference of object oriented methods corresponding to the plain old Function modules of classic abap.
    i was thinking, after seeing the blogs of people like Thomas Jung, Horst Keller, they encouraged a lot on abap objects over procedural abap. are there any such guidlines, references present to migrate (rather upgrade) to abap objects from existing procedural abap
    thanks,
    Madhu_1980

    I don't think it makes sense to do 1:1 mapping and replacement in your code.
    It does make sense to refactor using Object oriented techniques and patterns but it is usually a non-trivial task.

  • Instance methods faster than sync. static methods in threaded env?

    consider the following please:
    (-) i have "lots" of instances of a single Runnable class running concurrently..
    (-) each instance uses a common method: "exponential smoothing" and they do a lot of smoothing.
    so:
    (option #1): include a "smooth()" instance method in the Runnable class.
    (option #2): include a "smooth()" synchronized static method in the Runnable class.
    (option #3): create a MathUtility class, and have "smooth()" as an instance method in this class.
    (option #4): make "smooth()" a synchronized static method in the MathUtility class.
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??
    well, i can't image there would be a measurable difference so maybe i should not post.
    but, if there is a flaw in my thinking, please let me know.
    thanks.

    kogose wrote:
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".From an OOP point of view you should probably have a class that represents the data that provides a (non-static) smooth() method that either modifies the data or returns a new smoothed data object (depending on whether you want your data objects to be immutable or not).
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??No, methods are not "copied" for each instance. That just doesn't happen.
    well, i can't image there would be a measurable difference so maybe i should not post.If you don't know, then you should probably try it.
    but, if there is a flaw in my thinking, please let me know.The flaw in your thinking is that you can think that you can intuitively grasp the difference in performance of a change at that level.
    I have yet to meet anyone who can reliably do that.
    Performance optimization is not an intuitive task at that level and you should never do performance optimizations without proving that they are improvements for your particular use case.
    First part: Is the smooth() method really thread-unsafe? Does it use some shared state? My guess would be that it uses only local state and therefore doesn't need any synchronization at all. That would also be the fastest alternative, most likely.

  • Why is it necessary to create an instance via the static method?

    Hi,
    For some classes (such as java.util.regex.Pattern), we should call the class method (static method) in order to create an instance (object).
    For example, in order to conduct the pattern matching, we should use the java.util.regex.Pattern class as follows:
    Pattern p = Pattern.compile ("X[0-9]+X") ;
      // An instance of the Pattern class is created.
    Matcher m = p.matcher ("abcX1XYX23Xz") ;
    while ( m.find() ){
      System.out.println ( m.start() ) ;
    }where the compile static method in the Pattern class creates an instance and returns the pointer (reference) of it. We should NOT call
    the constructor of the Pattern class as follows:
    Pattern p = new Pattern ("X[0-9]+X") ;    // ERRORThe question is the following:
    (1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?
    (2) Why do the java.util.regex.Pattern class have such a specification?
    Thanks in advance.

    (1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?1. As the other author mentioned, caching is one reason.
    2. With such caching, you don't need to take trouble in passing the reference of a cached object(s) to many places in your code. From anywhere in your code base, you can simply invoke the method, the object will come. In essence, the static method provides a global point of access to one or more pre-created (or cached) objects. Hence, the static method simplifies access to the object.
    3. Sometimes, the actual class instantiated is not the same as the one with the static method. This allows abstraction of underlying variations. For example, when you say Pattern.compile ("X[0-9]+X") , the returned object type can be different in Windows and Linux (Most probably Pattern class doesn't work like that, but I am showing you a use case. May be Runtime.getRuntime() does actually work like that.). You find this abstraction of variations in many places. Take for example, FacesContext.getExternalContext() method (this is from JSF API). ExternalContext documentation says this:
    "This class allows the Faces API to be unaware of the nature of its containing application environment. In particular, this class allows JavaServer Faces based appications to run in either a Servlet or a Portlet environment."
    Edited by: Kamal Wickramanayake on Oct 24, 2012 8:04 AM

  • This static method cannot hide the instance method from...

    What means the error message "This static method cannot hide the instance method from Referee"?
    Referee.java is a interface. I implemented it in the class RefereeMyName.java and made a method in that class to be static. Thats why I received that error message.
    But can't I use static methods when I have implemented a interface in that class? I want to have a Player.java class which I want to access RefereeMyName.getTarget(). I cannot use a instance instead because I wouldn't receive a valid return value then (RefereeMyName is the client class).
    What is the solution?

    Hi,
    Well i do not think that you can do that b'cos that way you are not giving the same signature for the method as that exists in the interface. I do not know how other way it can be done but if something urgent for you then you can remove that method from that interface and only define in the class.
    Regards,
    Shishank

  • Static methods

    Is creating a static method frowned upon in OO development? Is it only a matter of convenience by not having to instantiate?
    Any insight is appreciated.
    --Gregory
    quote: Don't throw away the old bucket until you know whether the new one holds water.

    Regardless of how many objects you have created, there is only 1 copy of the static variables in the memory. Its not just a matter of convenience but is used in certain conditions based on some requirements. A good example would be Singleton. There already is a kind of Singleton class in the standard Java class libraries:
    the Math class. This is a class that is declared final and all methods are declared static, meaning that the class cannot be extended. The purpose of the Math class is to wrap a number of common mathematical functions such as sin and log in a class-like structure, since the Java language does not support functions that are not methods in a class. You can use the same approach to a Singleton pattern, making it a final class. You can�t create any instance of classes like Math, and can only call the static
    methods directly in the existing final class.
    Another approach, suggested by Design Patterns, is to create Singletons using a static method to issue and keep track of instances. To prevent instantiating the class more than once, we make the constructor private so an instance can only be created from within the static method of the class.
    Hope that helps
    &#9824

  • Static methods, or not...

    Ok, i've got a class with around 50 or so methods in it. im going to have around a hundred of these classes going at once. my question is: should i make all the methods static, and then pass in an instance of a class to work on? would that use less memory, or be beneficial in any way? im probably completely wrong, but i wanted to check anwyays, just in case..
    so, for example
    public void stuff(){
    x++;
    turning into
    public void stuff(SomeClass target){
    target.x++;
    }

    For each method there is (generally) one and only one implementation loaded into memory. Having 10 thousand instances of a class does not create copies 10 thousand copies of the methods. No, using static methods would be a waste of your energy and probably be a rather poor design.
    Chuck

  • Why there should not be many static methods.

    Why a java class should not have many static methods.How is memory managed in case of static methods.
    If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.

    shobhit123 wrote:
    Why a java class should not have many static methods.How is memory managed in case of static methods.
    If a Utility class has static methods then we can use methods directly by class name but if we do not make the methods static then we can acess methods using object.How does it make the difference.I know that there remains a single copy of class variables/methods.But i want to know how class memory is managed and garbage collected.The reason to discourage static methods is stylistic rather than technical. It encourages object oriented thinking.
    Each loaded class is represented by a Class object, and associated with that it a block of memory for static fields. As with all such storage this block is, as viewed from code, rather like an array with one, or in the case of double or long values, two slots per field.
    Because the class loader maintains a map from FQN to Class this storage is only released if the class loader that loaded it becomes unreachable, which happens only in situations like the un-deployment of a web application or EJB.
    Local variables for static methods are allocated in a stack frame, just as with instance methods. There's really no significant difference there.

Maybe you are looking for