Are java static fields multiple times when streaming?

I am working on a group project in which we have several static constants declared in the Worker class. Many threads of this worker are spawning and our java application seems to be using a huge amount of memory. I'm wondering if this is the result of each thread allocating more of these static constants, but I'm not sure.

+3


source to share


3 answers


No, there is only one instance of a static variable in ClassLoader.

 public class Foo {
      // only 1 of these
      private static int bar = 10;
 }

      



However, it is important to understand that this does not mean that the value is automatically synchronized. If threads change this value, then it must be synchronized

, otherwise they might see different values ​​according to race conditions.

+8


source


Static variables are not explicitly allocated based on the number of threads. Instead, static variables are allocated once within the ClassLoader class.



+1


source


If you are using a "huge" amount of memory, eg. many GB, I would use a memory profiler to find the cause and fix it if possible. If you are using several hundred MB, I would not bother with this unless you know what the problem is.

0


source







All Articles