DKSRathore
DKSRathore

Reputation: 3063

Is it possible to change the priority of garbage Collector thread?

Java garbage collector runs with priority 1, due to which it is not guaranteed that System.gc() will actually execute if called.

Is there any way to change its priority? This shall enable me to run if I want.

Upvotes: 0

Views: 3233

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533590

The GC will run as required. You shouldn't need to call it manually. If you don't like when it is run you can control it with command line arguments.

If you believe you have a problem with the behaviour of the GC you should try to fix the cause rather than trying to write your own work around.

In summary, you should tell us what is the real cause of your concern so we can address that.

Upvotes: 1

Pascal Thivent
Pascal Thivent

Reputation: 570395

Garbage Collector is an independent thread (as reminded by Tom Hawtin in a comment, not even necessarily a single thread) and is on a priority which is decided by the Java Virtual Machine. This means you can't force garbage collection. Calling System.gc() tells the runtime environment that "now" might be a good time to run the GC but garbage collection is actually not guaranteed to be done immediately.

Upvotes: 7

Diego Dias
Diego Dias

Reputation: 22616

When a thread is created it inherits the priority of the thread that created it. The priority of a thread can be adjusted by using

public final void setPriority(int newPriority)

The problem is a thread doesn't "run" the garbage collector. The garbage collector is run by the VM (when Java wants or is in "good mood .. :)" ).

EDIT: The GC is not a thread but a method of the Runtime thread. You can change the priority of the Runtime thread but this will have no effect on the GC. The thread that calls the GC is a thread of the VM and is out side the scope of the API so you can't change its priority.

So, I don't really think you can set its priority.

Upvotes: 0

Michael Lloyd Lee mlk
Michael Lloyd Lee mlk

Reputation: 14661

Even if you upped the thread priority to 11 System.gc will not guarantee anything. All you can be sure of is that if Java needs to GC it will before it throws an out of memory exception.

Upvotes: 4

Related Questions