简体   繁体   中英

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.

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.

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

If you are using a "huge" amount of memory eg many GB, I would use a memory profiler to find what the cause is and fix it if you can. If you are using a few hundred MB, I wouldn't worry about it unless you know this is a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM