Last active
August 29, 2015 14:17
-
-
Save yaroslav-ulanovych/0351f0cef2c8c687dda2 to your computer and use it in GitHub Desktop.
Proof that lambdas don't work with listeners on weak references.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo | |
import java.lang.ref.WeakReference | |
class Listeners[T] { | |
private var buffer = List[WeakReference[T => Unit]]() | |
def fire(e: T): Unit = { | |
buffer.map(_.get()).filter(_ ne null).foreach(_.apply(e)) | |
buffer = buffer.filter(_.get() ne null) | |
println("listeners: " + buffer.size) | |
} | |
def add(f: T => Unit): Unit = { | |
buffer = buffer :+ new WeakReference(f) | |
} | |
} | |
object Test extends App { | |
val listeners = new Listeners[Int] | |
listeners.add(e => println(e)) | |
listeners.fire(42) | |
System.gc() | |
listeners.fire(42) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment