简体   繁体   中英

how many Java Garbage Collector objects?

谁能告诉我,如果我们并行执行两个线程来调用垃圾收集器,那么会创建多少个gc对象?

总是只有一个垃圾收集器,在其自己的Thread中运行

There's one garbage collector as others pointed out.
You should not care about the count of the garbage collector objects
or about any details about the garbage collector. This is something
on JVM/system level. All you care about is when to call the garbage
collection explicitly (if you want to do that).

(This is responding to the OP's comments which reveal the nature of the misunderstanding that is at the root of his Question. See the quoted text ...)

yes Runtime is a singleton but when we are calling Runtime.gc(), ...

Correct

... the jvm internally it will created one thread that is garbage colletor(daemon thread).

Incorrect. It does not create a new GC thread. Rather it causes the existing GC thread to wake up and do a garbage collection. Furthermore:

  • the thread that calls gc() will not return until the garbage collector has completed.

  • depending on the garbage collector that has been configured, the garbage collector may freeze all other application threads before starting the collection.

... but in this case when we call gc in two different threads at a time, how many GC objects will be created?

None. If two methods call gc() at the same time, the GC will run once on the existing GC thread. Think of the GC as an "engine" that is either running or sleeping at any point in time. Calling gc() will typically cause the GC to start running if it is currently sleeping.

(Actually, I'm simplifying things a bit. CMS and G1 have the complication that the gc() will typically run in parallel with application threads. Another possibility is that the gc() call will be simply ignored. Finally, the GC typical has a variety of modes; eg a young generation collection, and a full collection. Calling gc() will start a full collection.)

... but we are saying that GC is daemon thread

Yes (sort of),

The GC may have multiple threads. There is typically a main GC thread, and another thread for handling finalization. And for some kinds of GC, some tasks are performed in parallel using a pool of threads.

and also gc() has native implementation

For mainstream JVMs, yes. (But as a counter-example, in JNode is implemented in Java, albeit using Unsafe methods, etc.)

then what is GC?

It is the "stuff" that does garbage collection. What actually goes on under the hood is JVM specific, and depends on JVM options, etcetera.

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