What are the benefits of using private static decorating methods?

Posted by jae_green on Sun, 10 May 2020 16:35:10 +0200

Recently, when modifying the business process, I encountered a method of modifying private static, calling another private method error in this method.

Non-static method 'sendAlarmMQ(java.lang.String, java.lang.String, java.lang.String)' cannot be referenced from a static context

 

Why the private static decoration method is used is summarized as follows:

  • Make it clear to the reader that they will not modify the state of the object.
  • The JIT compiler will always inline and optimize it. )

 

According to this elder, just to know clearly that the method cannot be changed by the object, at least the internal part of the method will not involve calling other methods, but simply do what you should do. Therefore, for this business modification, you need to call another private method within the static decorated method, so you cannot declare this method as static.

The second senior means that it seems to improve the performance, because static functions do not need to detect whether this pointer is empty. He also dedicated to give a sample and explained it from the level of instruction code.

class TestBytecodeSize {
    private void doSomething(int arg) { }
    private static void doSomethingStatic(int arg) { }
    public static void main(String[] args) {
        // do it twice both ways
        doSomethingStatic(0);
        doSomethingStatic(0);
        TestBytecodeSize t = new TestBytecodeSize();
        t.doSomething(0);
        t.doSomething(0);
    }
}

 

C:\Users\wx\Desktop\layout Import>javap -c TestBytecodeSize
Compiled from "TestBytecodeSize.java"
class TestBytecodeSize {
  TestBytecodeSize();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: invokestatic  #2                  // Method doSomethingStatic:(I)V
       4: iconst_0
       5: invokestatic  #2                  // Method doSomethingStatic:(I)V
       8: new           #3                  // class TestBytecodeSize
      11: dup
      12: invokespecial #4                  // Method "<init>":()V
      15: astore_1
      16: aload_1
      17: iconst_0
      18: invokespecial #5                  // Method doSomething:(I)V
      21: aload_1
      22: iconst_0
      23: invokespecial #5                  // Method doSomething:(I)V
      26: return
}

Original address: https://stackoverflow.com/questions/538870/should-private-helper-methods-be-static-if-they-can-be-static

In case of infringement, I will delete it in time

Topics: Java