need of Static variables and their overhead on jvm

前端 未结 3 936
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 00:03

As per the concept about static members, they are created/loaded into the memory when there is first call made to its class. And they are common among all instances of that

相关标签:
3条回答
  • 2021-01-07 00:17
    1. No, they are collected with the class.

    2. Overhead compared to what? What's the alternative?

    3. Yes, but nobody said you have to fill them up with static members.

    0 讨论(0)
  • 2021-01-07 00:20

    1) Static members are garbage collected only when the class that defines them is itself collected; this in turn can only happen if the defining ClassLoader is collected. This is common in web application containers and plugin architectures.

    2) Yes, defining a large amount of static data can be a bad idea. But it's like a lot of other things: it's good if you need it, and bad if you abuse it. Just use common sense.

    3) Again, an interface that defined an array of a thousand Strings would be a bad idea, but of course that's not normally what people do. Just use common sense. There's no (memory-related) reason to avoid static variables in general.

    0 讨论(0)
  • 2021-01-07 00:32
    1. yes. No GC will ever clean up static variables. This is important because otherwise one could not rely on values stored in static variables. Design patterns like "Singleton" rely on static variables.

    2. The static variables take as much mem as the same value stored in instance variable, so as long as the value stored in the variable is really necessary for the abblication, there is no particular storage overhead in static variables. But the side-effects iposed by the use of static variables when it comes to thread-safety etc. need to be considered more thatn the memory issues.

    3. yes. But Interfaces are there for describing the contract between provider and user of functionality, not for storing any data.

    0 讨论(0)
提交回复
热议问题