Advertisement
Guest User

Untitled

a guest
May 14th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.29 KB | None | 0 0
  1. import java.lang.ref.WeakReference
  2.  
  3.  
  4. fun main(args: Array<String>) {
  5.  
  6.     var fancyClass3: FancyClass? = FancyClass.get()
  7.     gc()
  8.     fancyClass3 = null
  9.     gc()
  10.     Thread.sleep(1000)
  11.  
  12.     var fancyClass: FancyClass? = FancyClass("should be garbage collectible")
  13.     gc()
  14.     fancyClass = null
  15.     gc()
  16.     Thread.sleep(1000)
  17.  
  18.     var fancyClass2: FancyClass? = FancyClass.get()
  19.     gc()
  20.     fancyClass2 = null
  21.     gc()
  22.     Thread.sleep(1000)
  23. }
  24.  
  25. fun gc() {
  26.     var obj: Any? = Any()
  27.     val ref = WeakReference<Any>(obj)
  28.     obj = null
  29.     while (ref.get() != null) {
  30.         System.gc()
  31.     }
  32. }
  33.  
  34. class FancyClass(private val description: String) {
  35.  
  36.     protected fun finalize() {
  37.         println("Goodbye my darling ($this : $description)")
  38.     }
  39.  
  40.     companion object : Provider<FancyClass>() {
  41.         override fun create(): FancyClass {
  42.             return FancyClass("shouldn't be garbage collectible")
  43.         }
  44.     }
  45.  
  46. }
  47.  
  48. /**
  49.  * Created by nicoladefiorenze on 22/03/18.
  50.  */
  51. abstract class Provider<T> {
  52.  
  53.     protected var original: T? = null
  54.  
  55.     var mocked: T? = null
  56.  
  57.     protected abstract fun create(): T
  58.  
  59.     fun get(): T = mocked ?: original ?: create()
  60.             .apply { original = this }
  61.  
  62.     fun lazyGet(): Lazy<T> = lazy { get() }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement