Dan Q
Dan Q

Reputation: 2257

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.

Upvotes: 3

Views: 784

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533432

If you are using a "huge" amount of memory e.g. 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.

Upvotes: 0

cdeszaq
cdeszaq

Reputation: 31280

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

Upvotes: 1

Gray
Gray

Reputation: 116828

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.

Upvotes: 8

Related Questions