Create java class not collectable by GC -


i want create class: - have 1 instance - accesible during lifetime of app. - class not have destroyed garbage collector.

can achive using static, or singleton pattern?

thanks

the way ensure class cannot garbage collected ensure remains reachable. could:

  • refer in class reachable,
  • load in initial classloader (which reachable),
  • put instance of class variable remains reachable,
  • etcetera.

in practice, unless class dynamically loaded using classloader created yourself, unlikely class unloaded / destroyed gc.


on other hand ... if concerned singleton instance (not class) being garbage collected, normal implementation of singleton design pattern takes care of that:

public class mysingleton {     private static integer instance = new integer(42);      public static integer getinstance() {         return instance;     } } 

the static variable reachable long mysingleton class remains reachable ... lifetime of application run; see above.

a public static variable work too, though bad idea other perspectives.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -