Collection with weak references

As mentioned in another question, I need to store listener references in a collection. To avoid memory leaks I thought it would be a good idea to use weak references. Are there any out-of-the-box collections using weak references in Scala?

UPDATE 1:
My - probably poor - first attempt to implement a weak list:

import scala.collection.immutable.AbstractSeq
import scala.ref.WeakReference

class WeakSeq[+A] private(private val seq: IndexedSeq[WeakReference[A]]) extends AbstractSeq[Option[A]] {
  override def apply(i: Int): Option[A] = seq(i).get

  override def length: Int = seq.length

  override def iterator: Iterator[Option[A]] = seq.map(ref => ref.get).filter(ref => ref.nonEmpty).iterator
}

object WeakSeq {
  def apply[A](elems: A*): WeakSeq[A] = {
    val seq = elems.map(WeakReference(_)).toIndexedSeq
    new WeakSeq(seq)
  }
}

(Sorry, I am not sure what the code formatted upsets here.)

Just curious… Keeping your listeners in weak references would mean they may be GC’ed if there are no hard references to them elsewhere. And you probably don’t want your listeners to be purged “in-flight” by arbitrary GC runs that can happen at any time…? Is it a valid assumption for your use case that there will be hard references elsewhere for the intended lifetime of all your listeners, is the presence of these listeners just optional and “nice to have”, or am I missing something else?

You are right, I never thought about that. I just had in mind to prevent memory leaks. But if the client implements its listener as anonymous class there might be no hard reference at all.

Thanks for the comment :slight_smile: