3

If I use stop-the-world GC and do some stuff in my finalize() method can I assume that all threads are suspended and I can do whatever I want and no thread will dare to compete for resources with me except the GC thread?

Nutel
  • 2,244
  • 2
  • 27
  • 50
  • 2
    *"no thread will dare to compete"* - I can just imagine the poor little application threads quivering in the corner, waiting for the big mean old GC thread to finish :-) – Stephen C Jul 16 '11 at 02:35

2 Answers2

4

No, in fact there may even be multiple finalizer threads running concurrently.

From the java language spec, "Finalizers may be called in any order, or even concurrently."

sbridges
  • 24,960
  • 4
  • 64
  • 71
2

No you can't - at least as far as I understand the hotspot implementation:

At least that's how it works with a mark&sweep gc, but I'm pretty sure it's similar to all other implementations as well:

After the sweep phase every unmarked finalized object is added to a work list with its mark bit set.

Then a background worker works through this list and after its finished with one finalize call clears the mark bit so that it's cleared by the next GC. As a consequence of this you can't make any assumptions about WHEN the finalize method will be called (actually since the background thread is probably stopped as well, you can be pretty sure that it's not while a GC run!).

Now that's a implementation detail for Hotspot and may even vary between different GC implementations..

Voo
  • 29,040
  • 11
  • 82
  • 156