Skip to content

Instantly share code, notes, and snippets.

@Ferada
Created May 6, 2019 10:28
Show Gist options
  • Save Ferada/cebca75459cf12d4e7a5dcc90392d72c to your computer and use it in GitHub Desktop.
Save Ferada/cebca75459cf12d4e7a5dcc90392d72c to your computer and use it in GitHub Desktop.
import java.lang.ref.ReferenceQueue
import java.lang.ref.WeakReference
import kotlin.concurrent.thread
class MyWeakReference<T>(val id: Int, p0: T, p1: ReferenceQueue<in T>?) : WeakReference<T>(p0, p1)
fun main() {
val queue = ReferenceQueue<Object>()
val upper = 10000000
val set = (1..upper).toMutableSet()
val t1 = thread {
val a = ArrayList<MyWeakReference<Object>>()
for (i in 1..upper) {
a.add(MyWeakReference(i, Object(), queue))
}
println("gc 1")
System.gc()
println("clear")
a.clear()
println("gc 2")
System.gc()
}
val t2 = thread {
while (true) {
val ref = queue.remove()
val id = (ref as MyWeakReference).id
synchronized(set) {
set.remove(id)
}
}
}
val t3 = thread {
while (true) {
println(set.size)
Thread.sleep(500)
}
}
t1.join()
t2.join()
t3.join()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment