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.

Similar Messages

  • Using a non-static vector in a generic class with static methods

    I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
    package genericset;
    import java.util.*;
    public class GenericSet<E>{
    private Vector v;
    public GenericSet(Vector vec) {
    v = vec;
    private <T extends Comparable> Item<T> get(int index) {
    return (Item<T>) v.get(index);
    public static <T extends Comparable> GenericSet<T> initialize() {
    return new GenericSet<T>(new Vector());
    public Vector getVector() {
    return v;
    public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (!member(g,i))
    v.addElement(i);
    return g;
    public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (member(g,i))
    v.remove(i);
    return g;
    public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
    Vector v = z.getVector();
    return v.contains(i);
    public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
    Vector v1 = z1.getVector();
    Vector v2 = z2.getVector();
    if((v1 == null) && (v2 != null))
    return false;
    return v1.equals(v2);
    public static <T extends Comparable> boolean empty(GenericSet<T> z) {
    return (cardinality(z) == 0);
    public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = assign(z1);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    insert(g, elem);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(!member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z); i++) {
    Item<T> elem = z.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    return false;
    return true;
    public static <T extends Comparable> int cardinality(GenericSet<T> z){
    Vector v = z.getVector();
    return v.size();
    }

    The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this:   public static EditorBean findEditorData( String username, EditorBean editorData )
          return editorData.ed.findEditor( username );
       }

  • Need Urgent Help with static methods!!!!

    If I have a static method to which a variable is being passed...for example
    static String doSomething(String str)
    //..doSomething with str and return
    If the method is invoked a second time by a separate entity when it is already in use by one entity(!!!not entity beans) .... will this lead to the second invocation overwriting str while the method is already in use and thus corrupting the variable that the method was passed from the first entity?

    It's also a common misunderstanding about parameters. The method does not receive a variable as its parameter, it receives a reference to an object. And inside the method, the parameter acts just the same as a local variable would. So if two threads call the method (static or not), each thread has its own copy of the parameter.

  • EasyMock 1.2 - working with static methods

    Hi,
    I'm working in an application which was written in java1.4. So we are using EasyMock 1.2 version since higher versions doesn't support java 1.4. I need to expect and return an array for a static method which is in a Util class (No interfaces involved). How can i do it with EasyMock 1.2?
    Any help would be much appreciated. Thanks.
    Edited by: user10996478 on Feb 28, 2012 7:06 AM

    If the guide doesn't explain it:
    http://easymock.org/EasyMock1_2_Java1_3_Documentation.html
    Then you have no choice but to use the source code of the API as the manual I'm afraid. I wouldn't hold my breath that you get help using a third party API which is incredibly outdated. The website mentions some yahoo group, perhaps you should attempt to see if it is still available and you can join it.

  • What's wrong with static methods?

    Answers on an postcard please.

    I think the point here is that sometimes people come from a procedural background (or maybe no background) and they start with main, and one static method leads to another. They reach a tipping point where they are reluctant to define non-static methods to a class because it's all static elsewhere. And static method can't access instance data, so their data becomes largely static as well. When the dust settles, they are programming procedually in Java. So too many static methods is a sign that you may be programming procedurally instead of doing OOP, but using static appropriately is still cool.
    And let's not get pedantic. What goes wrong if I make my String class's getLength method static?
    public final class MyString {
        private int length;
        public static int getLength(String s) {
            return s.length;
    }It's a misuse of static, but it doesn't break my design.

  • Interface with static methods

    I'm writting a wrapper for exception handling.One of the classes uses log4j to log exceptions.I want to write a interface to generalize loggin.Idealy I should have an interface with certain static methods for loging (i.e logError,logDebugMessage,consoleError,consoleMessage,etc) , but Interface dosent allow that and neither do abstract classes can havstatic method declarations.The implementations of these methods will achieve the hiding of the complexity of using a logging package,log levels etc from the user.
    Let me know how best I can work something out for this.
    Thanks in advance

    Define them once (as final) in an abstract class. Then any subclass can call logError etc.
    Kind regards,
      Levi

  • Singleton bottleneck with static methods?

    A discussion came up at work today. If a class is created as a Singleton and only provides static methods and only final static data members (just for storing read only info like a connection string), will this create a bottleneck? Someone was suggesting that sharing the Singleton would cause each thread accessing the code to have to obtain the monitor on the class before being able to execute the method. Is this the case? None of the methods are synchronized, but they all perform atomic functionality. Anyone have any input on this?

    Currenlty, it is implemented as a Singleton, part of
    the discussion was moving everything into static
    methods. Aside from that, the question is still
    whether having a single location to run methods from
    will become a bottleneckWho came up with the idea that this would create some sort of bottleneck? Never pay attention to them again.
    Static methods are (slightly) faster than ordinary instance methods because there is no virtual method lookup. The only way there would be some sort of performance implication is if the methods are synchronized. In that case performance will be essentially the same as synchronized instance methods of a singleton.

  • Memory Management with NSString and synthesized properties

    I thought I understood memory management but now I'm getting some odd behavior and that's the only thing I can see that I might be doing incorrectly:
    I have a synthesized NSString propery called displayText. At one point I attempt to set a label with the displayText property (label.text = [[note displayText]]). The first one works, but the second one does not:
    [note setDisplayText:[[note fileName]]]; // - works
    [note setDisplayText:[[self getCharacterInFileName:[[note fileName]]]]; // - does not work
    And here is getCharacterInFileName:
    // Given the fileName for the image, get the specific part of that fileName for the note letter
    - (NSString *)getCharacterInFileName:(NSString *)fileName
    NSRange range = {1,1};
    NSString *characterInString = [[[NSString alloc]] initWithString:[[fileName substringWithRange:range]]];
    return characterInString;
    Is there some pointer mismanagement going on here that I'm missing?
    Message was edited by: darkpegasus

    Nevermind, I'm an idiot. I forgot to close an if/else block with a brace and it screwed everything up.

  • Implementing interface with static method?

    Hi,
    I need to implement an interface with a static method. I tried to do it both with the interface method static and non-static, but it don't seam to work! Does it work?
    How can I make a work around?
    Thanks!

    Interfaces are designed to provide a contract that a particular object instance guarantees for it's Clients.
    Since a static method does not relate to any particular object instance there is no contract to define...hence you can't have an interface for static methods...
    What you could do however is return an object via a static method that does provide the implementation of the interface...
    i.e.public class MyClass
        static private String myInterfaceImpl = "<some class>";
        static public MyInterface getInterface ()
             return (MyInterface) MyClass.class.forName (MyClass.myInterfaceImpl).newInstance ();
    }That would return an object that provides the interface. I would presume you need the static method so that you don't have to pass around references to a particular object...this method gets around that...you could also create a single object at start up time and return a reference to that eveytime...
    Also, in a way static methods do define an interface...

  • 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...

  • Help with static method issue.

    Hi everyone,
    There's a recent thread on the forum along a similar vein as this one but I hope mine doesn't cause as much annoyance! My homework assignment involves implementing three interfaces provided by my professor in order to create weighted, undirected graphs. The classes I have to implement are Node, Edge and Graph. Here are the Edge and Node interfaces for reference; they weren't too hard to implement:
    public interface Edge {
         public Edge createEdge(String name, int ID, float weight);
         public Node getStartNode();
         public void setStartNode(Node n);
         public Node getEndNode();
         public void setEndNode(Node n);
         public String getName();
         public int getID();
         public float getWeight();
         public String toString();
    public interface Node {
         public Node createNode(String name, int ID, float weight);
         public Node[] getNeighbours();
         public Edge[] getEdges();
         public void addEdge(Edge e);
         public void removeEdge(Edge e);
         public String getName();
         public int getID();
         public float getWeight();
         public String toString();
    }Now, one of the graphs I should be aiming to create is this one ( [http://i35.tinypic.com/2iqn62d.gif|http://i35.tinypic.com/2iqn62d.gif] ) so I apologize for the code I'm about to show and its length. It's the Graph class:
    import java.util.ArrayList;
    public class Graph {
         public static void main(String [] args) {
              // Create all nodes
              int i = 1;
              Node food = new Node();
              food.createNode("Food", i, 0);
              i++;
              Node healthy = new Node();
              healthy.createNode("Healthy", i, 4f);
              i++;
              Node neutral = new Node();
              neutral.createNode("Neutral", i, 0);
              i++;
              Node unhealthy = new Node();
              unhealthy.createNode("Unhealthy", i, -4f);
              i++;
              Node orange = new Node();
              orange.createNode("Orange", i, 6f);
              i++;
              Node cabbage = new Node();
              unhealthy.createNode("Cabbage", i, 3f);
              i++;
              Node riceCake = new Node();
              unhealthy.createNode("Rice cake", i, 2f);
              i++;
              Node chocolate = new Node();
              unhealthy.createNode("Chocolate", i, -2f);
              i++;
              Node bacon = new Node();
              unhealthy.createNode("Bacon", i, -4f);
              i++;
              Node xmasPud = new Node();
              unhealthy.createNode("Christmas Pudding", i, -8f);
              i++;
              // Create all edges
              int n = 1;
              Edge food1 = new Edge();
              food1.createEdge("to healthy", i, -4.0f);
              food1.setStartNode(food);
              food1.setEndNode(healthy);
              n++;
              Edge food2 = new Edge();
              food2.createEdge("to neutral", i, 0);
              food2.setStartNode(food);
              food2.setEndNode(neutral);
              n++;
              Edge food3 = new Edge();
              food3.createEdge("to unhealthy", i, -4f);
              food3.setStartNode(food);
              food3.setEndNode(unhealthy);
              n++;
              Edge healthy1 = new Edge();
              healthy1.createEdge("to orange", i, 4f);
              healthy1.setStartNode(healthy);
              healthy1.setEndNode(orange);
              n++;
              Edge healthy2 = new Edge();
              healthy2.createEdge("to cabbage", i, 2f);
              healthy2.setStartNode(healthy);
              healthy2.setEndNode(cabbage);
              n++;
              Edge neutral1 = new Edge();
              neutral1.createEdge("to rice cake", i, 2f);
              neutral1.setStartNode(neutral);
              neutral1.setEndNode(riceCake);
              n++;
              Edge unhealthy1 = new Edge();
              unhealthy1.createEdge("to chocolate", i, -2f);
              unhealthy1.setStartNode(unhealthy);
              unhealthy1.setEndNode(chocolate);
              n++;
              Edge unhealthy2 = new Edge();
              unhealthy2.createEdge("to bacon", i, -4f);
              unhealthy2.setStartNode(unhealthy);
              unhealthy2.setEndNode(bacon);
              n++;
              Edge unhealthy3 = new Edge();
              unhealthy3.createEdge("to Christmas pudding", i, -8f);
              unhealthy3.setStartNode(unhealthy);
              unhealthy3.setEndNode(xmasPud);
              n++;
              // Assign edges to edgeList
              food.edgeList.add(food1);
              food.edgeList.add(food2);
              food.edgeList.add(food3);
              // Add node to nodeList
              nodeList.add(food);
              healthy.edgeList.add(healthy1);
              healthy.edgeList.add(healthy2);
              nodeList.add(healthy);
              neutral.edgeList.add(neutral1);
              nodeList.add(neutral);
              unhealthy.edgeList.add(unhealthy1);
              unhealthy.edgeList.add(unhealthy2);
              unhealthy.edgeList.add(unhealthy3);
              nodeList.add(unhealthy);
              // Now convert to arrays
              Node[] nodeArray = new Node; // Nodes
              nodeList.toArray(nodeArray);
              Edge[] edgeArray = new Edge[n]; // Edges
              food.edgeList.toArray(edgeArray);
              healthy.edgeList.toArray(edgeArray);
              unhealthy.edgeList.toArray(edgeArray);
              // Now turn it all into a graph
              createGraph("Food", 1, nodeArray, edgeArray, food); // doesn't work!
         public Graph createGraph(String name, int ID, Node[] nodes, Edge[] edges,
                   Node root) {
              graphName = name;
              graphID = ID;
              graphNodes = nodes;
              graphEdges = edges;
              graphRoot = root;
              return null;
         public String getName() {
              return graphName;
         public Edge[] getEdges() {
              return graphEdges;
         public void addEdge(Edge e) {
         public Edge getEdge(String name, int ID) {
              return null;
         public void removeEdge(Edge e) {
         public Node[] getNodes() {
              return graphNodes;
         public void addNode(Node n) {
              nodeList.add(n);
         public Node getNode(String name, int ID) {
              int ni = nodeList.indexOf(name);
              Node rNode = nodeList.get(ni);
              return rNode;
         public void removeNode(Node n) {
              nodeList.remove(n);
         public void setRoot(Node n) {
              graphRoot = n;
         public Node getRoot() {
              return graphRoot;
         private String graphName;
         private int graphID;
         private Node[] graphNodes;
         private Edge[] graphEdges;
         private Node graphRoot;
         private static ArrayList<Node> nodeList = new ArrayList<Node>();
    }The problem I have is that I don't know how to get around the fact that I'm making a static reference to the non-static method *createGraph*. I'd really appreciate your help. Thanks for your time!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    GiselleT wrote:
    public interface Edge {
         public Edge createEdge(String name, int ID, float weight);
    I want to kick your professor right in the grapes for this bit of idiocy. It's at the source of your problems.
    This looks very fishy and very bad. I wouldn't expect an Edge to create another Edge. Likewise for Node and Graph. You might have static factory methods in these classes, but by defining it in the interfaces, these methods have to be non-static. This leads to such ridiculous code as you have like this:
    Edge uselessEdge = new Edge();
    Edge actualEdge = uselessEdge.createEdge("abc", 1, 2.34);It's not your fault that it's useless. That's the way you have to do it with that senseless requirement.
    The problem I have is that I don't know how to get around the fact that I'm making a static reference to the non-static method createGraph.
    Static reference in non-static context errors are always addressed the same way: Either make the member in question static (usually the wrong choice) or create an instance.
    In this case, you need to do like you did with Edge, and create a useless dummy Graph whose only purpose is to create other Graphs:
    Graph graph = uselessGraph();
    Graph actualGraph = uselessGraph.createGraph(...);Then, inside the createGraph method, you'll create a Graph with new and do thatGraph.name = name; and so on for each of the parameters/members.
    Really, though, this is just an awful, awful approach though. Are you sure your prof really requires Edge to have a non-static createEdge method, and so on?

  • Campaigns with static method

    I have two questions regarding campaign
    1)I have configured campaign for update events of content.
    which will call static method of one class.but when any update occur in repository,exception comes for static method's class not found.
    2)How to avoid stop date in campaign.so that it will run always.
    Can anybody help me on the same

    Since the campaigns run in the enterprise app classloader, anything called by the campaign needs to run in this classloader as well (APP-INF/lib). You could perhaps promote the code you want to call from the campaign from the web-app classloader to the enterprise-app classloader if you want it to be called.
    Code in the enterprise-app classloader (APP-INF/...) can be called by code in the web-app classloader (WEB-INF/...) but not vice-versa. So it shouldn't be an issue to move the code to the ent-app classloader, and it can then be called by both the campaign as well as existing web-app code.
    -Steve

  • Advantages and disadvanteges with static methods

    Hi,
    Can anybody suggest me the advantages and disadvantages of static methods? In my project i am using templates which are used by different programs and in that templates i am using static methods.
    It is web application. is there any problems if made methods as static in templates that are used by diferent clients?
    Thanks
    Karimulla

    A static method can't be overridden, and static methods are usually only used for some utility methods and other things which don't belong to the class. I would probably not make the methods static.
    Kaj

  • Threading with static methods

    If I have a multithreading capabilities in my program, then I invoke a static method that writes timestamp to a file. What will happen? will all threads use this same static method? or will the program crash?

    static or otherwise isn't the issue. The issue is that it's not a good idea to have two threads trying to write to the same file at the same time.
    To prevent this you need to have each thread reserve the file until it's done it's thing. If you put the synchronized keyword on the method declaration you lock any all synchronized statis methods in the class, which is probably not idea. Probably better to use some comon object as the montor e.g.
    static File timeStamp = new File("timestamp.txt");
    public static void setTimeStamp() throws IOException {
         synchronized(timeStamp) {
              Writer out = new FileWriter(timeStamp);
              out.close();
         }

  • Use of Synchronised with Static methods in EJBs

    We have a number of classes whose static methods are called by multiple EJBs. Could you tell me whether I might need to Synchronise these static methods or will this be unnecessary because they are being called by an EJB for a specific user.
    Thanks
    Dave

    Whether or not a method (static or non-static) is thread-safe depends on whether or not the method accesses instance and/or class variables or only method-local variables...
    dave horner wrote:
    We have a number of classes whose static methods are called by multiple EJBs. Could you tell me whether I might need to Synchronise these static methods or will this be unnecessary because they are being called by an EJB for a specific user.
    Thanks
    Dave

Maybe you are looking for