Java Class instance method caller to static method.

Discussion in 'Plugin Development' started by spuddy, Oct 21, 2020.

Thread Status:
Not open for further replies.
  1. Offline

    spuddy

    When I make a class that is going to have multiple instances of it created, if that class has instance methods I'll generally "proxy" them (I guess that's the right word, I know Java has specific proxying APIs but this is more general and not related to that). Essentially, the public instance method is minimal, simply passing the instance of the class and the parameters to a private static method that does all the work. My reasoning for it was (this started many years ago) that I didn't want multiple instances of the same code for every class instance I make. Many many moons ago, I wrote a simple game server in Java which ended up having thousands of players. I was dismayed at how much memory the server required when so many players were on-line. After painstakingly editing all my classes this way, the memory usage dropped significantly. So ever since then I always implement class instance methods this way by habit.

    My question is, a lot of time since then has passed, does the Java VM deal with that sort of thing itself now? The reason I ask is that I performed a test with multiple instances of a class with regular instance methods and the same test with the proxying instance method to a static method. I made a few thousand instances of each class and noticed that the memory usage for both was practically the same. My plugin has a class representing a single Block and depending on what it's doing it may have to be dealing with thousands of them and this crossed my mind during testing. Do I still need to bother doing this these days?

    Code:
        instead of this...
        public Object makeThingsHappen(Object obj1, Object obj2) {
            ...
            ... tonnes of code doing loads of stuffs
            ...
            return returnObject;
        }
      
        this...
        public Object makeThingsHappen(Object obj1, Object obj2) {
            return makeThingsHappen(this, Object obj1, Object obj2);
        }
        private static makeThingsHappen(MyClass myClass, Object obj1, Object obj2) {
            ...
            ... tonnes of stuff doing loads of codes
            ... but now doing it on myClass
            ...
            return returnObject;  
        }
    Cheers for reading
    Spud..
     
    Last edited: Oct 22, 2020
  2. Offline

    Mathias Eklund

    When creating Objects in Java you should think about what that object is. If a paramater of the object is the same for all instances of that object, then you can make the parameter static. When it comes to function calls I think that keeping it static and giving it the object instance would be better.
     
Thread Status:
Not open for further replies.

Share This Page