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

后端 未结 4 975
花落未央
花落未央 2021-01-07 12:41

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 prio

相关标签:
4条回答
  • 2021-01-07 13:28

    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.

    0 讨论(0)
  • 2021-01-07 13:32

    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.

    0 讨论(0)
  • 2021-01-07 13:45

    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.

    0 讨论(0)
  • 2021-01-07 13:46

    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.

    0 讨论(0)
提交回复
热议问题