Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'finally' block in android run

Tags:

java

android

In android, for code under a finally block:

1548 finally {
1549                /*
1550                 * clean-up everything...
1551                 */
1552                synchronized (sGLThreadManager) {
1553                    stopEglSurfaceLocked();
1554                    stopEglContextLocked();
1555                }
1556            }

Does it mean it will be run by the 'FinalizerDaemon'?

And what does it mean when the trace.txt shows FinalizerDaemon is waiting on a ReferenceQueue?

  "FinalizerDaemon" daemon prio=5 tid=7 WAIT
  | group="system" sCount=1 dsCount=0 obj=0x419d0c60 self=0x50cf3650
  | sysTid=3933 nice=0 sched=0/0 cgrp=apps handle=1086157112
  | schedstat=( 0 0 0 ) utm=32 stm=9 core=1
  at java.lang.Object.wait(Native Method)
  - waiting on <0x416da5d0> (a java.lang.ref.ReferenceQueue)
  at java.lang.Object.wait(Object.java:401)
  at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:102)
  at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:73)
  at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:169)
  at java.lang.Thread.run(Thread.java:856)
like image 214
michael Avatar asked Dec 06 '25 17:12

michael


2 Answers

Finally is executed at the end of a try catch block regardless of whether or not an exception occurs.

FinalizerDaemon is not related to this. It is related to garbage collection.

like image 193
Eurig Jones Avatar answered Dec 08 '25 06:12

Eurig Jones


finally and finalizers are not related.

finally is a block of code after a try-catch block that will run regardless of the outcome of the try-catch. It's usually where you will find crucial cleanup code to prevent resource leakage.

Finalizers (an object's finalize() method) can be run by the garbage collector when the object is cleaned up. However, you're not guaranteed they'll run, nor run in any order, etc.

FinalizerDaemon is likely a thread that is running finalize() methods. In this case, it sounds like it's blocking on a ReferenceQueue, which is going to hold references to objects that are eligible to be finalized.

For what it's worth, there's no behavior here that is Android-specific; this is just Java behavior.

like image 30
RonU Avatar answered Dec 08 '25 06:12

RonU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!