Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.ref.WeakReference
- fun main(args: Array<String>) {
- var fancyClass3: FancyClass? = FancyClass.get()
- gc()
- fancyClass3 = null
- gc()
- Thread.sleep(1000)
- var fancyClass: FancyClass? = FancyClass("should be garbage collectible")
- gc()
- fancyClass = null
- gc()
- Thread.sleep(1000)
- var fancyClass2: FancyClass? = FancyClass.get()
- gc()
- fancyClass2 = null
- gc()
- Thread.sleep(1000)
- }
- fun gc() {
- var obj: Any? = Any()
- val ref = WeakReference<Any>(obj)
- obj = null
- while (ref.get() != null) {
- System.gc()
- }
- }
- class FancyClass(private val description: String) {
- protected fun finalize() {
- println("Goodbye my darling ($this : $description)")
- }
- companion object : Provider<FancyClass>() {
- override fun create(): FancyClass {
- return FancyClass("shouldn't be garbage collectible")
- }
- }
- }
- /**
- * Created by nicoladefiorenze on 22/03/18.
- */
- abstract class Provider<T> {
- protected var original: T? = null
- var mocked: T? = null
- protected abstract fun create(): T
- fun get(): T = mocked ?: original ?: create()
- .apply { original = this }
- fun lazyGet(): Lazy<T> = lazy { get() }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement