Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are java static fields allocated multiple times when threading?

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

like image 943
Dan Q Avatar asked Jul 04 '26 13:07

Dan Q


1 Answers

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

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

However, it is important to realize that this doesn't mean that the value is automagically synchronized. If the threads are changing this value then it needs to be synchronized otherwise they could see different values according to race conditions.

like image 65
Gray Avatar answered Jul 07 '26 03:07

Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!