本文整理汇总了Scala中java.lang.ref.WeakReference类的典型用法代码示例。如果您正苦于以下问题:Scala WeakReference类的具体用法?Scala WeakReference怎么用?Scala WeakReference使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WeakReference类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: transform
//设置package包名称以及导入依赖的类
package org.pico.event
import java.io.Closeable
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.{AtomicInteger, AtomicReference}
import org.pico.atomic.syntax.std.atomicReference._
import org.pico.disposal.OnClose
trait SimpleSinkSource[A, B] extends SinkSource[A, B] {
private final val subscribers = new AtomicReference(List.empty[WeakReference[B => Unit]])
private final val garbage = new AtomicInteger(0)
def transform: A => B
final override def publish(event: A): Unit = {
subscribers.get().foreach { subscriberRef =>
val subscriber = subscriberRef.get()
if (subscriber != null) {
subscriber(transform(event))
} else {
garbage.incrementAndGet()
}
}
houseKeep()
}
final override def subscribe(subscriber: B => Unit): Closeable = {
val subscriberRef = new WeakReference(subscriber)
subscribers.update(subscriberRef :: _)
houseKeep()
OnClose {
identity(subscriber)
subscriberRef.clear()
houseKeep()
}
}
final def houseKeep(): Unit = {
if (garbage.get() > subscribers.get().size) {
garbage.set(0)
subscribers.update { subscriptions =>
subscriptions.filter { subscription =>
subscription.get() != null
}
}
}
}
}