diff --git a/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala b/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala index 4f13e0d4154..7a5db844661 100644 --- a/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala +++ b/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala @@ -126,7 +126,8 @@ object BehaviorTestKitSpec { replyTo ! Done Behaviors.same case CreateMessageAdapter(messageClass, f, replyTo) => - val adaptor = context.messageAdapter(f)(ClassTag(messageClass)) + implicit val ct: ClassTag[Any] = ClassTag(messageClass) + val adaptor = context.messageAdapter[Any](f.asInstanceOf[Any => Command]) replyTo.foreach(_ ! adaptor.unsafeUpcast) Behaviors.same case Log(what) => diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/dns/DockerBindDnsService.scala b/actor-tests/src/test/scala/org/apache/pekko/io/dns/DockerBindDnsService.scala index ab27bb25142..501aa8a9e78 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/dns/DockerBindDnsService.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/dns/DockerBindDnsService.scala @@ -19,6 +19,7 @@ import scala.concurrent.duration._ import scala.jdk.CollectionConverters._ import scala.util.Try import scala.util.control.NonFatal + import com.github.dockerjava.api.DockerClient import com.github.dockerjava.api.async.ResultCallback import com.github.dockerjava.api.command.CreateContainerCmd @@ -29,10 +30,11 @@ import com.github.dockerjava.httpclient5.ApacheDockerHttpClient import org.apache.pekko import pekko.actor.Props import pekko.io.dns.internal.DnsClient +import pekko.testkit.PekkoSpec import pekko.util.Timeout -import pekko.testkit.PekkoSpec import org.scalatest.concurrent.Eventually + import com.typesafe.config.Config abstract class DockerBindDnsService(config: Config) extends PekkoSpec(config) with Eventually { diff --git a/actor-tests/src/test/scala/org/apache/pekko/util/SWARUtilSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/util/SWARUtilSpec.scala index a88d6b5e8fb..6ce67621375 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/util/SWARUtilSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/util/SWARUtilSpec.scala @@ -19,8 +19,8 @@ package org.apache.pekko.util import java.nio.ByteOrder -import org.scalatest.wordspec.AnyWordSpec import org.scalatest.matchers.should.Matchers +import org.scalatest.wordspec.AnyWordSpec class SWARUtilSpec extends AnyWordSpec with Matchers { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorContextSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorContextSpec.scala index bda008a2869..2b2b058e1d2 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorContextSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorContextSpec.scala @@ -83,7 +83,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp def decoration[T: ClassTag]: Behavior[T] => Behavior[T] implicit class BehaviorDecorator[T](behavior: Behavior[T])(implicit ev: ClassTag[T]) { - def decorate: Behavior[T] = decoration[T](ev)(behavior) + def decorate: Behavior[T] = decoration[T].apply(behavior) } "An ActorContext" must { @@ -661,7 +661,8 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp "not allow null messages" in { // Scala 3 doesn't generate an implicit `ClassTag[Null]` (https://github.com/lampepfl/dotty/issues/9586) - val actor = spawn(decoration(ClassTag.Null)(Behaviors.empty[Null])) + @nowarn("msg=never used") implicit val ct: ClassTag[Null] = ClassTag.Null + val actor = spawn(decoration[Null].apply(Behaviors.empty[Null])) intercept[InvalidMessageException] { actor ! null } diff --git a/actor-typed/src/main/scala-3/org/apache/pekko/actor/typed/internal/receptionist/Platform.scala b/actor-typed/src/main/scala-3/org/apache/pekko/actor/typed/internal/receptionist/Platform.scala index 1ae72d69214..6ee2282ddf1 100644 --- a/actor-typed/src/main/scala-3/org/apache/pekko/actor/typed/internal/receptionist/Platform.scala +++ b/actor-typed/src/main/scala-3/org/apache/pekko/actor/typed/internal/receptionist/Platform.scala @@ -23,11 +23,11 @@ import pekko.annotation.InternalApi @InternalApi private[receptionist] object Platform { type Aux[P] = AbstractServiceKey { type Protocol = P } - type Service[K <: Aux[_]] = K match { + type Service[K <: Aux[?]] = K match { case Aux[t] => ActorRef[t] } - type Subscriber[K <: Aux[_]] = K match { + type Subscriber[K <: Aux[?]] = K match { case Aux[t] => ActorRef[ReceptionistMessages.Listing[t]] } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Behavior.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Behavior.scala index 1c9cbcad670..bc0e070c846 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Behavior.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Behavior.scala @@ -98,8 +98,10 @@ class SuperviseBehavior[T] private[pekko] ( * * Only exceptions of the given type (and their subclasses) will be handled by this supervision behavior. */ - def onFailure[Thr <: Throwable](clazz: Class[Thr], strategy: SupervisorStrategy): SuperviseBehavior[T] = - onFailure(strategy)(ClassTag(clazz)) + def onFailure[Thr <: Throwable](clazz: Class[Thr], strategy: SupervisorStrategy): SuperviseBehavior[T] = { + implicit val ct: ClassTag[Thr] = ClassTag(clazz) + onFailure(strategy) + } private[pekko] def unwrap: Behavior[T] = wrapped } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ProducerController.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ProducerController.scala index 128321a009d..7d4368642eb 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ProducerController.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ProducerController.scala @@ -294,7 +294,8 @@ object ProducerController { messageClass: Class[A], producerId: String, durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { - apply(producerId, durableQueueBehavior.toScala)(ClassTag(messageClass)) + implicit val ct: ClassTag[A] = ClassTag(messageClass) + apply(producerId, durableQueueBehavior.toScala) } /** @@ -305,7 +306,8 @@ object ProducerController { producerId: String, durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]], settings: Settings): Behavior[Command[A]] = { - apply(producerId, durableQueueBehavior.toScala, settings)(ClassTag(messageClass)) + implicit val ct: ClassTag[A] = ClassTag(messageClass) + apply(producerId, durableQueueBehavior.toScala, settings) } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/WorkPullingProducerController.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/WorkPullingProducerController.scala index fd3554551f0..b3a63a58588 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/WorkPullingProducerController.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/WorkPullingProducerController.scala @@ -241,7 +241,8 @@ object WorkPullingProducerController { producerId: String, workerServiceKey: ServiceKey[ConsumerController.Command[A]], durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { - apply(producerId, workerServiceKey, durableQueueBehavior.toScala)(ClassTag(messageClass)) + implicit val ct: ClassTag[A] = ClassTag(messageClass) + apply(producerId, workerServiceKey, durableQueueBehavior.toScala) } /** @@ -253,6 +254,7 @@ object WorkPullingProducerController { workerServiceKey: ServiceKey[ConsumerController.Command[A]], durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]], settings: Settings): Behavior[Command[A]] = { - apply(producerId, workerServiceKey, durableQueueBehavior.toScala, settings)(ClassTag(messageClass)) + implicit val ct: ClassTag[A] = ClassTag(messageClass) + apply(producerId, workerServiceKey, durableQueueBehavior.toScala, settings) } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/eventstream/EventStream.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/eventstream/EventStream.scala index 51f6ccd18d3..07190a07c49 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/eventstream/EventStream.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/eventstream/EventStream.scala @@ -59,7 +59,8 @@ object EventStream { /** * Java API. */ - def this(clazz: Class[E], subscriber: ActorRef[E]) = this(subscriber)(ClassTag(clazz)) + def this(clazz: Class[E], subscriber: ActorRef[E]) = + this(subscriber)(ClassTag(clazz)) /** * INTERNAL API diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ActorContextImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ActorContextImpl.scala index 6f2e98b9627..7f3842dff36 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ActorContextImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ActorContextImpl.scala @@ -123,7 +123,7 @@ import org.slf4j.LoggerFactory timer } - protected[this] def mkTimer(): TimerSchedulerCrossDslSupport[T] = new TimerSchedulerImpl[T](this) + protected def mkTimer(): TimerSchedulerCrossDslSupport[T] = new TimerSchedulerImpl[T](this) override private[pekko] def hasTimer: Boolean = _timer.isDefined diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/Supervision.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/Supervision.scala index 19fc70b43bf..396637bd2b6 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/Supervision.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/Supervision.scala @@ -43,7 +43,8 @@ import org.slf4j.event.Level * INTERNAL API */ @InternalApi private[pekko] object Supervisor { - def apply[T, Thr <: Throwable: ClassTag](initialBehavior: Behavior[T], strategy: SupervisorStrategy): Behavior[T] = { + def apply[T, Thr <: Throwable](initialBehavior: Behavior[T], strategy: SupervisorStrategy)( + implicit ev: ClassTag[Thr]): Behavior[T] = { if (initialBehavior.isInstanceOf[scaladsl.AbstractBehavior[?]] || initialBehavior .isInstanceOf[javadsl.AbstractBehavior[?]]) { diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/Behaviors.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/Behaviors.scala index 78a3d5314ee..d4425cd4a5e 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/Behaviors.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/Behaviors.scala @@ -31,10 +31,10 @@ import pekko.japi.pf.PFBuilder */ object Behaviors { - private[this] val _two2same = new JapiFunction2[ActorContext[Any], Any, Behavior[Any]] { + private val _two2same = new JapiFunction2[ActorContext[Any], Any, Behavior[Any]] { override def apply(context: ActorContext[Any], msg: Any): Behavior[Any] = same } - private[this] def two2same[T] = _two2same.asInstanceOf[JapiFunction2[ActorContext[T], T, Behavior[T]]] + private def two2same[T] = _two2same.asInstanceOf[JapiFunction2[ActorContext[T], T, Behavior[T]]] /** * `setup` is a factory for a behavior. Creation of the behavior instance is deferred until @@ -234,8 +234,10 @@ object Behaviors { * @param monitor The messages will also be sent to this `ActorRef` * @param behavior The inner behavior that is decorated */ - def monitor[T](interceptMessageClass: Class[T], monitor: ActorRef[T], behavior: Behavior[T]): Behavior[T] = - scaladsl.Behaviors.monitor(monitor, behavior)(ClassTag(interceptMessageClass)) + def monitor[T](interceptMessageClass: Class[T], monitor: ActorRef[T], behavior: Behavior[T]): Behavior[T] = { + implicit val ct: ClassTag[T] = ClassTag(interceptMessageClass) + scaladsl.Behaviors.monitor(monitor, behavior) + } /** * Behavior decorator that logs all messages to the [[pekko.actor.typed.Behavior]] using the provided @@ -332,8 +334,10 @@ object Behaviors { def transformMessages[Outer, Inner]( interceptMessageClass: Class[Outer], behavior: Behavior[Inner], - selector: JFunction[PFBuilder[Outer, Inner], PFBuilder[Outer, Inner]]): Behavior[Outer] = - BehaviorImpl.transformMessages(behavior, selector.apply(new PFBuilder).build())(ClassTag(interceptMessageClass)) + selector: JFunction[PFBuilder[Outer, Inner], PFBuilder[Outer, Inner]]): Behavior[Outer] = { + implicit val ct: ClassTag[Outer] = ClassTag(interceptMessageClass) + BehaviorImpl.transformMessages(behavior, selector.apply(new PFBuilder).build()) + } /** * Support for scheduled `self` messages in an actor. @@ -413,7 +417,8 @@ object Behaviors { asScalaMap(mdcForMessage.apply(message)) } - WithMdcBehaviorInterceptor[T](asScalaMap(staticMdc), mdcForMessageFun, behavior)(ClassTag(interceptMessageClass)) + implicit val ct: ClassTag[T] = ClassTag(interceptMessageClass) + WithMdcBehaviorInterceptor[T](asScalaMap(staticMdc), mdcForMessageFun, behavior) } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/pubsub/Topic.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/pubsub/Topic.scala index 98ee992ea86..10cd1ddc075 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/pubsub/Topic.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/pubsub/Topic.scala @@ -134,7 +134,9 @@ object Topic { /** * Java API: Create a topic actor behavior for the given topic name and message class */ - def create[T](messageClass: Class[T], topicName: String): Behavior[Command[T]] = - apply[T](topicName)(ClassTag(messageClass)) + def create[T](messageClass: Class[T], topicName: String): Behavior[Command[T]] = { + implicit val ct: ClassTag[T] = ClassTag(messageClass) + apply[T](topicName) + } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AskPattern.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AskPattern.scala index 5ab409bccbe..1fff9cc5b99 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AskPattern.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AskPattern.scala @@ -119,8 +119,8 @@ object AskPattern { // We do not currently use the implicit scheduler, but want to require it // because it might be needed when we move to a 'native' typed runtime, see #24219 ref match { - case a: InternalRecipientRef[Req] => askClassic[Req, Res](a, timeout, replyTo) - case a => + case a: (InternalRecipientRef[Req] @unchecked) => askClassic[Req, Res](a, timeout, replyTo) + case a => throw new IllegalStateException( "Only expect references to be RecipientRef, ActorRefAdapter or ActorSystemAdapter until " + "native system is implemented: " + a.getClass) @@ -144,7 +144,7 @@ object AskPattern { private final class PromiseRef[U](target: InternalRecipientRef[?], timeout: Timeout) { // Note: _promiseRef mustn't have a type pattern, since it can be null - private[this] val (_ref: ActorRef[U], _future: Future[U], _promiseRef) = + private val (_ref: ActorRef[U], _future: Future[U], _promiseRef) = if (target.isTerminated) ( adapt.ActorRefAdapter[U](target.provider.deadLetters), diff --git a/actor/src/main/scala-3/org/apache/pekko/util/ByteIterator.scala b/actor/src/main/scala-3/org/apache/pekko/util/ByteIterator.scala index dd727215ee7..3e2d80f3cfb 100644 --- a/actor/src/main/scala-3/org/apache/pekko/util/ByteIterator.scala +++ b/actor/src/main/scala-3/org/apache/pekko/util/ByteIterator.scala @@ -256,28 +256,28 @@ object ByteIterator { override def getShort(implicit byteOrder: ByteOrder): Short = { val cur = current if cur.len >= java.lang.Short.BYTES then { - val r = cur.getShort(byteOrder) + val r = cur.getShort(using byteOrder) normalize() r - } else super.getShort(byteOrder) + } else super.getShort(using byteOrder) } override def getInt(implicit byteOrder: ByteOrder): Int = { val cur = current if cur.len >= java.lang.Integer.BYTES then { - val r = cur.getInt(byteOrder) + val r = cur.getInt(using byteOrder) normalize() r - } else super.getInt(byteOrder) + } else super.getInt(using byteOrder) } override def getLong(implicit byteOrder: ByteOrder): Long = { val cur = current if cur.len >= java.lang.Long.BYTES then { - val r = cur.getLong(byteOrder) + val r = cur.getLong(using byteOrder) normalize() r - } else super.getLong(byteOrder) + } else super.getLong(using byteOrder) } final override def len: Int = iterators.foldLeft(0) { _ + _.len } @@ -417,19 +417,19 @@ object ByteIterator { getToArray(xs, offset, n, 1) { getByte } { current.getBytes(_, _, _) } def getShorts(xs: Array[Short], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 2) { getShort(byteOrder) } { current.getShorts(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 2) { getShort(using byteOrder) } { current.getShorts(_, _, _)(using byteOrder) } def getInts(xs: Array[Int], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 4) { getInt(byteOrder) } { current.getInts(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 4) { getInt(using byteOrder) } { current.getInts(_, _, _)(using byteOrder) } def getLongs(xs: Array[Long], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getLong(byteOrder) } { current.getLongs(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8) { getLong(using byteOrder) } { current.getLongs(_, _, _)(using byteOrder) } def getFloats(xs: Array[Float], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getFloat(byteOrder) } { current.getFloats(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8) { getFloat(using byteOrder) } { current.getFloats(_, _, _)(using byteOrder) } def getDoubles(xs: Array[Double], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getDouble(byteOrder) } { current.getDoubles(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8) { getDouble(using byteOrder) } { current.getDoubles(_, _, _)(using byteOrder) } /** For performance sensitive code, call copyToBuffer() directly on ByteString (it's optimised there) */ override def copyToBuffer(buffer: ByteBuffer): Int = { @@ -649,10 +649,10 @@ abstract class ByteIterator extends BufferedIterator[Byte] { } def getFloat(implicit byteOrder: ByteOrder): Float = - java.lang.Float.intBitsToFloat(getInt(byteOrder)) + java.lang.Float.intBitsToFloat(getInt(using byteOrder)) def getDouble(implicit byteOrder: ByteOrder): Double = - java.lang.Double.longBitsToDouble(getLong(byteOrder)) + java.lang.Double.longBitsToDouble(getLong(using byteOrder)) /** * Get a specific number of Bytes from this iterator. In contrast to @@ -690,7 +690,7 @@ abstract class ByteIterator extends BufferedIterator[Byte] { * Get a number of Shorts from this iterator. */ def getShorts(xs: Array[Short])(implicit byteOrder: ByteOrder): this.type = - getShorts(xs, 0, xs.length)(byteOrder) + getShorts(xs, 0, xs.length)(using byteOrder) /** * Get a number of Shorts from this iterator. @@ -701,7 +701,7 @@ abstract class ByteIterator extends BufferedIterator[Byte] { * Get a number of Ints from this iterator. */ def getInts(xs: Array[Int])(implicit byteOrder: ByteOrder): this.type = - getInts(xs, 0, xs.length)(byteOrder) + getInts(xs, 0, xs.length)(using byteOrder) /** * Get a number of Ints from this iterator. @@ -712,7 +712,7 @@ abstract class ByteIterator extends BufferedIterator[Byte] { * Get a number of Longs from this iterator. */ def getLongs(xs: Array[Long])(implicit byteOrder: ByteOrder): this.type = - getLongs(xs, 0, xs.length)(byteOrder) + getLongs(xs, 0, xs.length)(using byteOrder) /** * Get a number of Longs from this iterator. @@ -723,7 +723,7 @@ abstract class ByteIterator extends BufferedIterator[Byte] { * Get a number of Floats from this iterator. */ def getFloats(xs: Array[Float])(implicit byteOrder: ByteOrder): this.type = - getFloats(xs, 0, xs.length)(byteOrder) + getFloats(xs, 0, xs.length)(using byteOrder) /** * Get a number of Floats from this iterator. @@ -734,7 +734,7 @@ abstract class ByteIterator extends BufferedIterator[Byte] { * Get a number of Doubles from this iterator. */ def getDoubles(xs: Array[Double])(implicit byteOrder: ByteOrder): this.type = - getDoubles(xs, 0, xs.length)(byteOrder) + getDoubles(xs, 0, xs.length)(using byteOrder) /** * Get a number of Doubles from this iterator. diff --git a/actor/src/main/scala/org/apache/pekko/actor/Actor.scala b/actor/src/main/scala/org/apache/pekko/actor/Actor.scala index 28e0b5e65a1..404c7e40e07 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Actor.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Actor.scala @@ -339,7 +339,7 @@ object Status { * }}} */ trait ActorLogging { this: Actor => - private var _log: LoggingAdapter = _ + private var _log: LoggingAdapter = null def log: LoggingAdapter = { // only used in Actor, i.e. thread safe diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorCell.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorCell.scala index 7f853edd8ef..7d36e058895 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorCell.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorCell.scala @@ -430,7 +430,7 @@ private[pekko] class ActorCell( with dungeon.DeathWatch with dungeon.FaultHandling { - private[this] var _props = _initialProps + private var _props = _initialProps def props: Props = _props import ActorCell._ @@ -445,11 +445,11 @@ private[pekko] class ActorCell( override final def classicActorContext: ActorContext = this protected def uid: Int = self.path.uid - private[this] var _actor: Actor = _ + private var _actor: Actor = _ def actor: Actor = _actor var currentMessage: Envelope = _ private var behaviorStack: List[Actor.Receive] = emptyBehaviorStack - private[this] var sysmsgStash: LatestFirstSystemMessageList = SystemMessageList.LNil + private var sysmsgStash: LatestFirstSystemMessageList = SystemMessageList.LNil // Java API final def getParent() = parent diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorRef.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorRef.scala index abd9d06af65..9f347390097 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorRef.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorRef.scala @@ -886,8 +886,8 @@ private[pekko] class VirtualPathContainer( // AddressTerminatedTopic must be updated together with the variables here. // Important: don't include calls to sendSystemMessage inside the synchronized since that can // result in deadlock, see issue #26326 - private[this] var watching = ActorCell.emptyActorRefSet - private[this] var _watchedBy: OptionVal[Set[ActorRef]] = OptionVal.Some(ActorCell.emptyActorRefSet) + private var watching = ActorCell.emptyActorRefSet + private var _watchedBy: OptionVal[Set[ActorRef]] = OptionVal.Some(ActorCell.emptyActorRefSet) /** * INTERNAL API diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorRefProvider.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorRefProvider.scala index 472adfbf4ad..8655e38bf88 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorRefProvider.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorRefProvider.scala @@ -418,7 +418,7 @@ private[pekko] class LocalActorRefProvider private[pekko] ( override val ignoreRef: ActorRef = new IgnoreActorRef(this) - private[this] final val terminationPromise: Promise[Terminated] = Promise[Terminated]() + private final val terminationPromise: Promise[Terminated] = Promise[Terminated]() def terminationFuture: Future[Terminated] = terminationPromise.future @@ -494,7 +494,7 @@ private[pekko] class LocalActorRefProvider private[pekko] ( * but it also requires these references to be @volatile and lazy. */ @volatile - private var system: ActorSystemImpl = _ + private var system: ActorSystemImpl = null @volatile private var extraNames: Map[String, InternalActorRef] = Map() diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorSystem.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorSystem.scala index cc0ae959a9d..9c5accd751f 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorSystem.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorSystem.scala @@ -979,7 +979,7 @@ private[pekko] class ActorSystemImpl( dynamicAccess.createInstanceFor[LoggingFilter](LoggingFilter, arguments).get } - private[this] val markerLogging = + private val markerLogging = new MarkerLoggingAdapter(eventStream, getClass.getName + "(" + name + ")", this.getClass, logFilter) val log: LoggingAdapter = markerLogging @@ -1018,7 +1018,7 @@ private[pekko] class ActorSystemImpl( val dispatcher: ExecutionContextExecutor = dispatchers.defaultGlobalDispatcher - private[this] final val terminationCallbacks = new TerminationCallbacks(provider.terminationFuture)(dispatcher) + private final val terminationCallbacks = new TerminationCallbacks(provider.terminationFuture)(dispatcher) override def whenTerminated: Future[Terminated] = terminationCallbacks.terminationFuture override def getWhenTerminated: CompletionStage[Terminated] = whenTerminated.asJava @@ -1323,8 +1323,8 @@ private[pekko] class ActorSystemImpl( } final class TerminationCallbacks[T](upStreamTerminated: Future[T])(implicit ec: ExecutionContext) { - private[this] final val done = Promise[T]() - private[this] final val ref = new AtomicReference(done) + private final val done = Promise[T]() + private final val ref = new AtomicReference(done) // onComplete never fires twice so safe to avoid null check upStreamTerminated.onComplete { t => diff --git a/actor/src/main/scala/org/apache/pekko/actor/FSM.scala b/actor/src/main/scala/org/apache/pekko/actor/FSM.scala index 49aef7c78bd..fd93a273b7c 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/FSM.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/FSM.scala @@ -131,7 +131,7 @@ object FSM { private[pekko] final case class Timer(name: String, msg: Any, mode: TimerMode, generation: Int, owner: AnyRef)( context: ActorContext) extends NoSerializationVerificationNeeded { - private var ref: Option[Cancellable] = _ + private var ref: Option[Cancellable] = None private val scheduler = context.system.scheduler private implicit val executionContext: ExecutionContextExecutor = context.dispatcher @@ -733,9 +733,9 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { /* * FSM State data and current timeout handling */ - private var currentState: State = _ + private var currentState: State = null private var timeoutFuture: Option[Cancellable] = None - private var nextState: State = _ + private var nextState: State = null private var generation: Long = 0L /* diff --git a/actor/src/main/scala/org/apache/pekko/actor/IndirectActorProducer.scala b/actor/src/main/scala/org/apache/pekko/actor/IndirectActorProducer.scala index fa6ec6f4a5f..39dec1dae9d 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/IndirectActorProducer.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/IndirectActorProducer.scala @@ -105,7 +105,7 @@ private[pekko] class TypedCreatorFunctionConsumer(clz: Class[? <: Actor], creato */ private[pekko] class ArgsReflectConstructor(clz: Class[? <: Actor], args: immutable.Seq[Any]) extends IndirectActorProducer { - private[this] val constructor = Reflect.findConstructor(clz, args) + private val constructor = Reflect.findConstructor(clz, args) override def actorClass = clz override def produce() = Reflect.instantiate(constructor, args) } diff --git a/actor/src/main/scala/org/apache/pekko/actor/LightArrayRevolverScheduler.scala b/actor/src/main/scala/org/apache/pekko/actor/LightArrayRevolverScheduler.scala index eb7ee9921d9..2d4e409501f 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/LightArrayRevolverScheduler.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/LightArrayRevolverScheduler.scala @@ -357,7 +357,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac } object LightArrayRevolverScheduler { - private[this] val taskHandle: VarHandle = { + private val taskHandle: VarHandle = { val lookup = MethodHandles.privateLookupIn(classOf[TaskHolder], MethodHandles.lookup()) lookup.findVarHandle(classOf[TaskHolder], "task", classOf[Runnable]) } @@ -417,8 +417,8 @@ object LightArrayRevolverScheduler { override def isCancelled: Boolean = task eq CancelledTask } - private[this] val CancelledTask = new Runnable { def run = () } - private[this] val ExecutedTask = new Runnable { def run = () } + private val CancelledTask = new Runnable { def run = () } + private val ExecutedTask = new Runnable { def run = () } private val NotCancellable: TimerTask = new TimerTask { def cancel(): Boolean = false diff --git a/actor/src/main/scala/org/apache/pekko/actor/Props.scala b/actor/src/main/scala/org/apache/pekko/actor/Props.scala index 69f2ef1f79c..2d8c4abf467 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Props.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Props.scala @@ -127,11 +127,11 @@ final case class Props(deploy: Deploy, clazz: Class[?], args: immutable.Seq[Any] // derived property, does not need to be serialized @transient - private[this] var _producer: IndirectActorProducer = _ + private var _producer: IndirectActorProducer = null // derived property, does not need to be serialized @transient - private[this] var _cachedActorClass: Class[? <: Actor] = _ + private var _cachedActorClass: Class[? <: Actor] = null /** * INTERNAL API @@ -143,7 +143,7 @@ final case class Props(deploy: Deploy, clazz: Class[?], args: immutable.Seq[Any] _producer } - private[this] def cachedActorClass: Class[? <: Actor] = { + private def cachedActorClass: Class[? <: Actor] = { if (_cachedActorClass eq null) _cachedActorClass = producer.actorClass diff --git a/actor/src/main/scala/org/apache/pekko/actor/RepointableActorRef.scala b/actor/src/main/scala/org/apache/pekko/actor/RepointableActorRef.scala index f9d300d9b73..0e9e562d812 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/RepointableActorRef.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/RepointableActorRef.scala @@ -212,13 +212,13 @@ private[pekko] class UnstartedCell( * This lock protects all accesses to this cell’s queues. It also ensures * safe switching to the started ActorCell. */ - private[this] final val lock = new ReentrantLock + private final val lock = new ReentrantLock // use Envelope to keep on-send checks in the same place ACCESS MUST BE PROTECTED BY THE LOCK - private[this] final val queue = new JLinkedList[Envelope]() + private final val queue = new JLinkedList[Envelope]() // ACCESS MUST BE PROTECTED BY THE LOCK - private[this] var sysmsgQueue: LatestFirstSystemMessageList = SystemMessageList.LNil + private var sysmsgQueue: LatestFirstSystemMessageList = SystemMessageList.LNil import systemImpl.settings.UnstartedPushTimeout.{ duration => timeout } @@ -305,7 +305,7 @@ private[pekko] class UnstartedCell( def isLocal = true - private[this] final def cellIsReady(cell: Cell): Boolean = (cell ne this) && (cell ne null) + private final def cellIsReady(cell: Cell): Boolean = (cell ne this) && (cell ne null) def hasMessages: Boolean = locked { val cell = self.underlying @@ -317,7 +317,7 @@ private[pekko] class UnstartedCell( if (cellIsReady(cell)) cell.numberOfMessages else queue.size } - private[this] final def locked[T](body: => T): T = { + private final def locked[T](body: => T): T = { lock.lock() try body finally lock.unlock() diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/AbstractDispatcher.scala b/actor/src/main/scala/org/apache/pekko/dispatch/AbstractDispatcher.scala index a0ed462f10b..f5e9e277dcc 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/AbstractDispatcher.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/AbstractDispatcher.scala @@ -116,8 +116,8 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator val mailboxes = prerequisites.mailboxes val eventStream = prerequisites.eventStream - @nowarn @volatile private[this] var _inhabitantsDoNotCallMeDirectly: Long = _ // DO NOT TOUCH! - @nowarn @volatile private[this] var _shutdownScheduleDoNotCallMeDirectly: Int = _ // DO NOT TOUCH! + @nowarn @volatile private var _inhabitantsDoNotCallMeDirectly: Long = _ // DO NOT TOUCH! + @nowarn @volatile private var _shutdownScheduleDoNotCallMeDirectly: Int = _ // DO NOT TOUCH! @nowarn private def _preventPrivateUnusedErasure = { _inhabitantsDoNotCallMeDirectly _shutdownScheduleDoNotCallMeDirectly diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/BatchingExecutor.scala b/actor/src/main/scala/org/apache/pekko/dispatch/BatchingExecutor.scala index d0f0ec0fa1f..93d278a00af 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/BatchingExecutor.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/BatchingExecutor.scala @@ -65,9 +65,9 @@ private[pekko] trait Batchable extends Runnable { private[pekko] trait BatchingExecutor extends Executor { // invariant: if "_tasksLocal.get ne null" then we are inside Batch.run; if it is null, we are outside - private[this] val _tasksLocal = new ThreadLocal[AbstractBatch]() + private val _tasksLocal = new ThreadLocal[AbstractBatch]() - private[this] abstract class AbstractBatch extends java.util.ArrayDeque[Runnable](4) with Runnable { + private abstract class AbstractBatch extends java.util.ArrayDeque[Runnable](4) with Runnable { @tailrec final def processBatch(batch: AbstractBatch): Unit = if ((batch eq this) && !batch.isEmpty) { batch.pollFirst().run() @@ -84,7 +84,7 @@ private[pekko] trait BatchingExecutor extends Executor { } } - private[this] final class Batch extends AbstractBatch { + private final class Batch extends AbstractBatch { override final def run(): Unit = { require(_tasksLocal.get eq null) _tasksLocal.set(this) // Install ourselves as the current batch @@ -97,9 +97,9 @@ private[pekko] trait BatchingExecutor extends Executor { } } - private[this] val _blockContext = new ThreadLocal[BlockContext]() + private val _blockContext = new ThreadLocal[BlockContext]() - private[this] final class BlockableBatch extends AbstractBatch with BlockContext { + private final class BlockableBatch extends AbstractBatch with BlockContext { // this method runs in the delegate ExecutionContext's thread override final def run(): Unit = { require(_tasksLocal.get eq null) diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/ForkJoinExecutorConfigurator.scala b/actor/src/main/scala/org/apache/pekko/dispatch/ForkJoinExecutorConfigurator.scala index ff500c16ac2..3a88f3136bb 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/ForkJoinExecutorConfigurator.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/ForkJoinExecutorConfigurator.scala @@ -15,11 +15,11 @@ package org.apache.pekko.dispatch import java.util.concurrent.{ ExecutorService, ForkJoinPool, ForkJoinTask, ThreadFactory, TimeUnit } -import com.typesafe.config.Config - import org.apache.pekko.annotation.InternalApi import org.apache.pekko.util.JavaVersion +import com.typesafe.config.Config + object ForkJoinExecutorConfigurator { /** diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/Mailbox.scala b/actor/src/main/scala/org/apache/pekko/dispatch/Mailbox.scala index 6dc048430e6..af728fabf93 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/Mailbox.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/Mailbox.scala @@ -88,7 +88,7 @@ private[pekko] abstract class Mailbox(val messageQueue: MessageQueue) * stay as it is. */ @volatile - var actor: ActorCell = _ + var actor: ActorCell = null def setActor(cell: ActorCell): Unit = actor = cell def dispatcher: MessageDispatcher = actor.dispatcher @@ -116,10 +116,10 @@ private[pekko] abstract class Mailbox(val messageQueue: MessageQueue) def numberOfMessages: Int = messageQueue.numberOfMessages @volatile - protected var _statusDoNotCallMeDirectly: Status = _ // 0 by default + protected var _statusDoNotCallMeDirectly: Status = 0 // 0 by default @volatile - protected var _systemQueueDoNotCallMeDirectly: SystemMessage = _ // null by default + protected var _systemQueueDoNotCallMeDirectly: SystemMessage = null // null by default // volatile read: the status is published across threads via compareAndSet/setVolatile // below; a plain VarHandle.get could observe a stale status (e.g. miss a Scheduled or diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/affinity/AffinityPool.scala b/actor/src/main/scala/org/apache/pekko/dispatch/affinity/AffinityPool.scala index 35d10b36ca0..4262c2ae614 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/affinity/AffinityPool.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/affinity/AffinityPool.scala @@ -62,17 +62,17 @@ private[affinity] object AffinityPool { // Following are auxiliary class and trait definitions private final class IdleStrategy(idleCpuLevel: Int) { - private[this] val maxSpins = 1100 * idleCpuLevel - 1000 - private[this] val maxYields = 5 * idleCpuLevel - private[this] val minParkPeriodNs = 1 - private[this] val maxParkPeriodNs = MICROSECONDS.toNanos(250 - ((80 * (idleCpuLevel - 1)) / 3)) + private val maxSpins = 1100 * idleCpuLevel - 1000 + private val maxYields = 5 * idleCpuLevel + private val minParkPeriodNs = 1 + private val maxParkPeriodNs = MICROSECONDS.toNanos(250 - ((80 * (idleCpuLevel - 1)) / 3)) - private[this] var state: IdleState = Initial - private[this] var turns = 0L - private[this] var parkPeriodNs = 0L - @volatile private[this] var idling = false + private var state: IdleState = Initial + private var turns = 0L + private var parkPeriodNs = 0L + @volatile private var idling = false - private[this] def transitionTo(newState: IdleState): Unit = { + private def transitionTo(newState: IdleState): Unit = { state = newState turns = 0 } @@ -148,8 +148,8 @@ private[pekko] class AffinityPool( // indicates the current state of the pool @volatile final private var poolState: PoolState = Uninitialized - private[this] final val workQueues = Array.fill(parallelism)(new BoundedAffinityTaskQueue(affinityGroupSize)) - private[this] final val workers = mutable.Set[AffinityPoolWorker]() + private final val workQueues = Array.fill(parallelism)(new BoundedAffinityTaskQueue(affinityGroupSize)) + private final val workers = mutable.Set[AffinityPoolWorker]() def start(): this.type = { bookKeepingLock.lock() @@ -263,7 +263,7 @@ private[pekko] class AffinityPool( override def toString: String = s"${Logging.simpleName(this)}(id = $id, parallelism = $parallelism, affinityGroupSize = $affinityGroupSize, threadFactory = $threadFactory, idleCpuLevel = $idleCpuLevel, queueSelector = $queueSelector, rejectionHandler = $rejectionHandler)" - private[this] final class AffinityPoolWorker(val q: BoundedAffinityTaskQueue, val idleStrategy: IdleStrategy) + private final class AffinityPoolWorker(val q: BoundedAffinityTaskQueue, val idleStrategy: IdleStrategy) extends Runnable { val thread: Thread = threadFactory.newThread(this) @@ -427,7 +427,7 @@ private[pekko] final class ThrowOnOverflowRejectionHandler extends RejectionHand private[pekko] final class FairDistributionHashCache(val config: Config) extends QueueSelectorFactory { private final val MaxFairDistributionThreshold = 2048 - private[this] final val fairDistributionThreshold = config + private final val fairDistributionThreshold = config .getInt("fair-work-distribution.threshold") .requiring( thr => 0 <= thr && thr <= MaxFairDistributionThreshold, @@ -437,7 +437,7 @@ private[pekko] final class FairDistributionHashCache(val config: Config) extends new AtomicReference[ImmutableIntMap](ImmutableIntMap.empty) with QueueSelector { override def toString: String = s"FairDistributionHashCache(fairDistributionThreshold = $fairDistributionThreshold)" - private[this] final def improve(h: Int): Int = + private final def improve(h: Int): Int = 0x7FFFFFFF & (reverseBytes(h * 0x9E3775CD) * 0x9E3775CD) // `sbhash`: In memory of Phil Bagwell. override final def getQueue(command: Runnable, queues: Int): Int = { val runnableHash = command.hashCode() diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/sysmsg/SystemMessage.scala b/actor/src/main/scala/org/apache/pekko/dispatch/sysmsg/SystemMessage.scala index 1e7b3e2ae13..803f81c6858 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/sysmsg/SystemMessage.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/sysmsg/SystemMessage.scala @@ -202,7 +202,7 @@ private[pekko] class EarliestFirstSystemMessageList(val head: SystemMessage) ext private[pekko] sealed trait SystemMessage extends PossiblyHarmful with Serializable { // Next fields are only modifiable via the SystemMessageList value class @transient - private[sysmsg] var next: SystemMessage = _ + private[sysmsg] var next: SystemMessage = null def unlink(): Unit = next = null diff --git a/actor/src/main/scala/org/apache/pekko/event/Logging.scala b/actor/src/main/scala/org/apache/pekko/event/Logging.scala index 7a1ef230638..2cfefc1f27e 100644 --- a/actor/src/main/scala/org/apache/pekko/event/Logging.scala +++ b/actor/src/main/scala/org/apache/pekko/event/Logging.scala @@ -51,7 +51,7 @@ trait LoggingBus extends ActorEventBus { private val guard = new ReentrantLock() private var loggers = Seq.empty[ActorRef] - @volatile private var _logLevel: LogLevel = _ + @volatile private var _logLevel: LogLevel = OffLevel /** * Query currently set log level. See object Logging for more information. diff --git a/actor/src/main/scala/org/apache/pekko/io/DirectByteBufferPool.scala b/actor/src/main/scala/org/apache/pekko/io/DirectByteBufferPool.scala index 50595a4d0af..6331b9ebec8 100644 --- a/actor/src/main/scala/org/apache/pekko/io/DirectByteBufferPool.scala +++ b/actor/src/main/scala/org/apache/pekko/io/DirectByteBufferPool.scala @@ -36,8 +36,8 @@ trait BufferPool { * benefit to wrapping in-heap JVM data when writing with NIO. */ private[pekko] class DirectByteBufferPool(defaultBufferSize: Int, maxPoolEntries: Int) extends BufferPool { - private[this] val pool: Array[ByteBuffer] = new Array[ByteBuffer](maxPoolEntries) - private[this] var buffersInPool: Int = 0 + private val pool: Array[ByteBuffer] = new Array[ByteBuffer](maxPoolEntries) + private var buffersInPool: Int = 0 def acquire(): ByteBuffer = takeBufferFromPool() diff --git a/actor/src/main/scala/org/apache/pekko/io/SelectionHandler.scala b/actor/src/main/scala/org/apache/pekko/io/SelectionHandler.scala index 338b823b87c..c6e2f869cf5 100644 --- a/actor/src/main/scala/org/apache/pekko/io/SelectionHandler.scala +++ b/actor/src/main/scala/org/apache/pekko/io/SelectionHandler.scala @@ -153,12 +153,12 @@ private[io] object SelectionHandler { settings: SelectionHandlerSettings, log: LoggingAdapter) extends ChannelRegistry { - private[this] val selector = SelectorProvider.provider.openSelector - private[this] val wakeUp = new AtomicBoolean(false) + private val selector = SelectorProvider.provider.openSelector + private val wakeUp = new AtomicBoolean(false) final val OP_READ_AND_WRITE = OP_READ | OP_WRITE // compile-time constant - private[this] val select = new Task { + private val select = new Task { def tryRun(): Unit = { if (selector.select(MaxSelectMillis) > 0) { // This assumes select return value == selectedKeys.size val keys = selector.selectedKeys @@ -317,9 +317,9 @@ private[io] class SelectionHandler(settings: SelectionHandlerSettings) import SelectionHandler._ import settings._ - private[this] var sequenceNumber = 0L // should be Long to prevent overflow - private[this] var childCount = 0 - private[this] val registry = { + private var sequenceNumber = 0L // should be Long to prevent overflow + private var childCount = 0 + private val registry = { val dispatcher = context.system.dispatchers.lookup(SelectorDispatcher) new ChannelRegistryImpl(SerializedSuspendableExecutionContext(dispatcher.throughput)(dispatcher), settings, log) } diff --git a/actor/src/main/scala/org/apache/pekko/io/SimpleDnsCache.scala b/actor/src/main/scala/org/apache/pekko/io/SimpleDnsCache.scala index c175aee614a..27e735ff2fa 100644 --- a/actor/src/main/scala/org/apache/pekko/io/SimpleDnsCache.scala +++ b/actor/src/main/scala/org/apache/pekko/io/SimpleDnsCache.scala @@ -34,9 +34,11 @@ private[io] trait PeriodicCacheCleanup { class SimpleDnsCache extends Dns with PeriodicCacheCleanup with NoSerializationVerificationNeeded { import SimpleDnsCache._ + private implicit val expiryOrdering: Ordering[ExpiryEntry[(String, RequestType)]] = + expiryEntryOrdering[(String, RequestType)]() private val cacheRef = new AtomicReference( new Cache[(String, RequestType), Resolved]( - immutable.SortedSet()(expiryEntryOrdering()), + immutable.SortedSet.empty[ExpiryEntry[(String, RequestType)]], immutable.Map(), () => clock())) diff --git a/actor/src/main/scala/org/apache/pekko/io/Tcp.scala b/actor/src/main/scala/org/apache/pekko/io/Tcp.scala index 38ec52095fc..70d7ced59ce 100644 --- a/actor/src/main/scala/org/apache/pekko/io/Tcp.scala +++ b/actor/src/main/scala/org/apache/pekko/io/Tcp.scala @@ -395,7 +395,7 @@ object Tcp extends ExtensionId[TcpExt] with ExtensionIdProvider { def iterator: Iterator[SimpleWriteCommand] = new Iterator[SimpleWriteCommand] { - private[this] var current: WriteCommand = CompoundWrite.this + private var current: WriteCommand = CompoundWrite.this def hasNext: Boolean = current ne null def next(): SimpleWriteCommand = current match { @@ -632,7 +632,7 @@ class TcpExt(system: ExtendedActorSystem) extends IO.Extension { case _ => getBoolean("windows-connection-abort-workaround-enabled") } - private[this] def getIntBytes(path: String): Int = { + private def getIntBytes(path: String): Int = { val size = getBytes(path) require(size < Int.MaxValue, s"$path must be < 2 GiB") require(size >= 0, s"$path must be non-negative") diff --git a/actor/src/main/scala/org/apache/pekko/io/TcpConnection.scala b/actor/src/main/scala/org/apache/pekko/io/TcpConnection.scala index cc8f4947046..839dfcfff1f 100644 --- a/actor/src/main/scala/org/apache/pekko/io/TcpConnection.scala +++ b/actor/src/main/scala/org/apache/pekko/io/TcpConnection.scala @@ -48,12 +48,12 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha import tcp.Settings._ import tcp.bufferPool - private[this] var pendingWrite: PendingWrite = EmptyPendingWrite - private[this] var peerClosed = false - private[this] var writingSuspended = false - private[this] var readingSuspended = pullMode - private[this] var interestedInResume: Option[ActorRef] = None - private[this] var closedMessage: Option[CloseInformation] = None // for ConnectionClosed message in postStop + private var pendingWrite: PendingWrite = EmptyPendingWrite + private var peerClosed = false + private var writingSuspended = false + private var readingSuspended = pullMode + private var interestedInResume: Option[ActorRef] = None + private var closedMessage: Option[CloseInformation] = None // for ConnectionClosed message in postStop private var watchedActor: ActorRef = context.system.deadLetters private var registration: Option[ChannelRegistration] = None @@ -364,7 +364,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha case _: SocketException => false } - @tailrec private[this] def extractMsg(t: Throwable): String = + @tailrec private def extractMsg(t: Throwable): String = if (t eq null) "unknown" else { t.getMessage match { diff --git a/actor/src/main/scala/org/apache/pekko/io/Udp.scala b/actor/src/main/scala/org/apache/pekko/io/Udp.scala index f2cb936ee07..995f463f4f5 100644 --- a/actor/src/main/scala/org/apache/pekko/io/Udp.scala +++ b/actor/src/main/scala/org/apache/pekko/io/Udp.scala @@ -217,7 +217,7 @@ object Udp extends ExtensionId[UdpExt] with ExtensionIdProvider { override val MaxChannelsPerSelector: Int = if (MaxChannels == -1) -1 else math.max(MaxChannels / NrOfSelectors, 1) - private[this] def getIntBytes(path: String): Int = { + private def getIntBytes(path: String): Int = { val size = getBytes(path) require(size < Int.MaxValue, s"$path must be < 2 GiB") size.toInt diff --git a/actor/src/main/scala/org/apache/pekko/pattern/AskSupport.scala b/actor/src/main/scala/org/apache/pekko/pattern/AskSupport.scala index 6de334f1f41..8c85c4eff0f 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/AskSupport.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/AskSupport.scala @@ -536,11 +536,11 @@ private[pekko] final class PromiseActorRef( */ @volatile @nowarn("msg=is never updated") - private[this] var _stateDoNotCallMeDirectly: AnyRef = _ + private var _stateDoNotCallMeDirectly: AnyRef = null @volatile @nowarn("msg=is never updated") - private[this] var _watchedByDoNotCallMeDirectly: immutable.Set[ActorRef] = ActorCell.emptyActorRefSet + private var _watchedByDoNotCallMeDirectly: immutable.Set[ActorRef] = ActorCell.emptyActorRefSet @nowarn private def _preventPrivateUnusedErasure = { _stateDoNotCallMeDirectly @@ -548,38 +548,38 @@ private[pekko] final class PromiseActorRef( } // volatile read: published across threads via compareAndSet in updateWatchedBy - private[this] def watchedBy: Set[ActorRef] = watchedByHandle.getVolatile(this) + private def watchedBy: Set[ActorRef] = watchedByHandle.getVolatile(this) - private[this] def updateWatchedBy(oldWatchedBy: Set[ActorRef], newWatchedBy: Set[ActorRef]): Boolean = + private def updateWatchedBy(oldWatchedBy: Set[ActorRef], newWatchedBy: Set[ActorRef]): Boolean = watchedByHandle.compareAndSet(this, oldWatchedBy, newWatchedBy) @tailrec // Returns false if the Promise is already completed - private[this] final def addWatcher(watcher: ActorRef): Boolean = watchedBy match { + private final def addWatcher(watcher: ActorRef): Boolean = watchedBy match { case null => false case other => updateWatchedBy(other, other + watcher) || addWatcher(watcher) } @tailrec - private[this] final def remWatcher(watcher: ActorRef): Unit = watchedBy match { + private final def remWatcher(watcher: ActorRef): Unit = watchedBy match { case null => () case other => if (!updateWatchedBy(other, other - watcher)) remWatcher(watcher) } @tailrec - private[this] final def clearWatchers(): Set[ActorRef] = watchedBy match { + private final def clearWatchers(): Set[ActorRef] = watchedBy match { case null => ActorCell.emptyActorRefSet case other => if (!updateWatchedBy(other, null)) clearWatchers() else other } // volatile read: published across threads via compareAndSet/setVolatile below - private[this] def state: AnyRef = stateHandle.getVolatile(this) + private def state: AnyRef = stateHandle.getVolatile(this) - private[this] def updateState(oldState: AnyRef, newState: AnyRef): Boolean = + private def updateState(oldState: AnyRef, newState: AnyRef): Boolean = stateHandle.compareAndSet(this, oldState, newState) // volatile write: ordered against the concurrent reads in state; restores the // putObjectVolatile semantics this had before the VarHandle migration - private[this] def setState(newState: AnyRef): Unit = stateHandle.setVolatile(this, newState) + private def setState(newState: AnyRef): Unit = stateHandle.setVolatile(this, newState) override def getParent: InternalActorRef = provider.tempContainer diff --git a/actor/src/main/scala/org/apache/pekko/pattern/CircuitBreaker.scala b/actor/src/main/scala/org/apache/pekko/pattern/CircuitBreaker.scala index 7b9f81f0df9..c64f76909d2 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/CircuitBreaker.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/CircuitBreaker.scala @@ -261,14 +261,14 @@ class CircuitBreaker( */ @nowarn("msg=is never updated") @volatile - private[this] var _currentStateDoNotCallMeDirectly: State = Closed + private var _currentStateDoNotCallMeDirectly: State = Closed /** * Holds reference to current resetTimeout of CircuitBreaker - *access only via helper methods* */ @nowarn("msg=is never updated") @volatile - private[this] var _currentResetTimeoutDoNotCallMeDirectly: FiniteDuration = resetTimeout + private var _currentResetTimeoutDoNotCallMeDirectly: FiniteDuration = resetTimeout @nowarn private def _preventPrivateUnusedErasure = { _currentStateDoNotCallMeDirectly @@ -282,7 +282,7 @@ class CircuitBreaker( * @param newState Next state on transition * @return Whether the previous state matched correctly */ - private[this] def swapState(oldState: State, newState: State): Boolean = + private def swapState(oldState: State, newState: State): Boolean = AbstractCircuitBreaker.stateHandle.compareAndSet(this, oldState, newState) /** @@ -290,7 +290,7 @@ class CircuitBreaker( * * @return Reference to current state */ - private[this] def currentState: State = + private def currentState: State = // volatile read: state is published across threads via compareAndSet in swapState; // restores the getObjectVolatile semantics this had before the VarHandle migration AbstractCircuitBreaker.stateHandle.getVolatile(this) @@ -298,13 +298,13 @@ class CircuitBreaker( /** * Helper method for updating the underlying resetTimeout via VarHandle */ - private[this] def swapResetTimeout(oldResetTimeout: FiniteDuration, newResetTimeout: FiniteDuration): Boolean = + private def swapResetTimeout(oldResetTimeout: FiniteDuration, newResetTimeout: FiniteDuration): Boolean = AbstractCircuitBreaker.resetTimeoutHandle.compareAndSet(this, oldResetTimeout, newResetTimeout) /** * Helper method for accessing to the underlying resetTimeout via VarHandle */ - private[this] def currentResetTimeout: FiniteDuration = + private def currentResetTimeout: FiniteDuration = // volatile read: see currentState; published via compareAndSet in swapResetTimeout AbstractCircuitBreaker.resetTimeoutHandle.getVolatile(this) diff --git a/actor/src/main/scala/org/apache/pekko/pattern/Patterns.scala b/actor/src/main/scala/org/apache/pekko/pattern/Patterns.scala index f56faed9683..1920d29efd2 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/Patterns.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/Patterns.scala @@ -129,7 +129,7 @@ object Patterns { */ def askWithReplyTo(actor: ActorRef, messageFactory: japi.function.Function[ActorRef, Any], timeout: Timeout) : Future[AnyRef] = - extended.ask(actor, messageFactory.apply _)(timeout).asInstanceOf[Future[AnyRef]] + extended.ask(actor, ref => messageFactory.apply(ref))(timeout).asInstanceOf[Future[AnyRef]] /** * A variation of ask which allows to implement "replyTo" pattern by including @@ -150,7 +150,8 @@ object Patterns { actor: ActorRef, messageFactory: japi.function.Function[ActorRef, Any], timeout: java.time.Duration): CompletionStage[AnyRef] = - extended.ask(actor, messageFactory.apply _)(Timeout.create(timeout)).asJava.asInstanceOf[CompletionStage[AnyRef]] + extended.ask(actor, ref => messageFactory.apply(ref))(Timeout.create(timeout)).asJava.asInstanceOf[CompletionStage[ + AnyRef]] /** * Java API for `org.apache.pekko.pattern.ask`: @@ -201,7 +202,7 @@ object Patterns { actor: ActorRef, messageFactory: japi.function.Function[ActorRef, Any], timeoutMillis: Long): Future[AnyRef] = - extended.ask(actor, messageFactory.apply _)(Timeout(timeoutMillis.millis)).asInstanceOf[Future[AnyRef]] + extended.ask(actor, ref => messageFactory.apply(ref))(Timeout(timeoutMillis.millis)).asInstanceOf[Future[AnyRef]] /** * Java API for `org.apache.pekko.pattern.ask`: @@ -316,7 +317,8 @@ object Patterns { selection: ActorSelection, messageFactory: japi.function.Function[ActorRef, Any], timeoutMillis: Long): Future[AnyRef] = - extended.ask(selection, messageFactory.apply _)(Timeout(timeoutMillis.millis)).asInstanceOf[Future[AnyRef]] + extended.ask(selection, ref => messageFactory.apply(ref))(Timeout(timeoutMillis.millis)).asInstanceOf[Future[ + AnyRef]] /** * A variation of ask which allows to implement "replyTo" pattern by including @@ -333,7 +335,8 @@ object Patterns { selection: ActorSelection, messageFactory: japi.function.Function[ActorRef, Any], timeout: java.time.Duration): CompletionStage[AnyRef] = - extended.ask(selection, messageFactory.apply _)(timeout.toScala).asJava.asInstanceOf[CompletionStage[AnyRef]] + extended.ask(selection, ref => messageFactory.apply(ref))(timeout.toScala).asJava.asInstanceOf[CompletionStage[ + AnyRef]] /** * Register an onComplete callback on this [[scala.concurrent.Future]] to send diff --git a/actor/src/main/scala/org/apache/pekko/routing/ConsistentHash.scala b/actor/src/main/scala/org/apache/pekko/routing/ConsistentHash.scala index 4020daae4aa..343970fa552 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/ConsistentHash.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/ConsistentHash.scala @@ -138,7 +138,8 @@ object ConsistentHash { */ def create[T](nodes: java.lang.Iterable[T], virtualNodesFactor: Int): ConsistentHash[T] = { import scala.jdk.CollectionConverters._ - apply(nodes.asScala, virtualNodesFactor)(ClassTag(classOf[Any].asInstanceOf[Class[T]])) + implicit val ct: ClassTag[T] = ClassTag.Any.asInstanceOf[ClassTag[T]] + apply(nodes.asScala, virtualNodesFactor) } private def concatenateNodeHash(nodeHash: Int, vnode: Int): Int = { diff --git a/actor/src/main/scala/org/apache/pekko/serialization/Serialization.scala b/actor/src/main/scala/org/apache/pekko/serialization/Serialization.scala index 6a0301af64c..9515ec1b238 100644 --- a/actor/src/main/scala/org/apache/pekko/serialization/Serialization.scala +++ b/actor/src/main/scala/org/apache/pekko/serialization/Serialization.scala @@ -150,7 +150,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { val settings = new Settings(system.settings.config) val AllowJavaSerialization: Boolean = system.settings.AllowJavaSerialization - private[this] val _log = Logging.withMarker(system, getClass.getName) + private val _log = Logging.withMarker(system, getClass.getName) val log: LoggingAdapter = _log private val manifestCache = new AtomicReference[Map[String, Option[Class[?]]]](Map.empty[String, Option[Class[?]]]) diff --git a/actor/src/main/scala/org/apache/pekko/serialization/Serializer.scala b/actor/src/main/scala/org/apache/pekko/serialization/Serializer.scala index 01cc91c3814..39275ef6a7b 100644 --- a/actor/src/main/scala/org/apache/pekko/serialization/Serializer.scala +++ b/actor/src/main/scala/org/apache/pekko/serialization/Serializer.scala @@ -382,9 +382,9 @@ final case class DisabledJavaSerializer(system: ExtendedActorSystem) extends Ser // use same identifier as JavaSerializer, since it's a replacement override val identifier: Int = BaseSerializer.identifierFromConfig(classOf[JavaSerializer], system) - private[this] val empty = Array.empty[Byte] + private val empty = Array.empty[Byte] - private[this] val log = Logging.withMarker(system, classOf[DisabledJavaSerializer]) + private val log = Logging.withMarker(system, classOf[DisabledJavaSerializer]) def includeManifest: Boolean = false diff --git a/actor/src/main/scala/org/apache/pekko/util/ByteString.scala b/actor/src/main/scala/org/apache/pekko/util/ByteString.scala index 44db0e80c75..6afa9791158 100644 --- a/actor/src/main/scala/org/apache/pekko/util/ByteString.scala +++ b/actor/src/main/scala/org/apache/pekko/util/ByteString.scala @@ -1083,7 +1083,7 @@ object ByteString { first.length + second.length == length, s"ByteString2 length ${first.length + second.length} did not match $length") - private[this] val firstLength: Int = first.length + private val firstLength: Int = first.length def apply(idx: Int): Byte = if (0 <= idx && idx < length) { @@ -1338,7 +1338,7 @@ object ByteString { ByteString1C(result) } - private[this] def byteAt(offset: Int, firstLength: Int): Byte = + private def byteAt(offset: Int, firstLength: Int): Byte = if (offset < firstLength) first.byteAtUnchecked(offset) else second.byteAtUnchecked(offset - firstLength) private[pekko] override def byteAtUnchecked(offset: Int): Byte = { @@ -2759,7 +2759,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { import ByteString.{ ByteString1, ByteString1C, ByteString2, ByteStrings } private var _length: Int = 0 private val _builder: VectorBuilder[ByteString1] = new VectorBuilder[ByteString1]() - private var _temp: Array[Byte] = _ + private var _temp: Array[Byte] = null private var _tempLength: Int = 0 private var _tempCapacity: Int = 0 @@ -2852,7 +2852,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { case bs: ByteString => addAll(bs) case xs: WrappedArray.ofByte => if (xs.nonEmpty) putByteArrayUnsafe(xs.array.clone) - case seq: collection.IndexedSeq[Byte] if shouldResizeTempFor(seq.length) => + case seq: (collection.IndexedSeq[Byte] @unchecked) if shouldResizeTempFor(seq.length) => if (seq.nonEmpty) { val copied = Array.from(xs) @@ -2860,7 +2860,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { _builder += ByteString.ByteString1(copied) _length += seq.length } - case seq: collection.IndexedSeq[Byte] => + case seq: (collection.IndexedSeq[Byte] @unchecked) => if (seq.nonEmpty) { ensureTempSize(_tempLength + seq.size) seq.copyToArray(_temp, _tempLength) diff --git a/actor/src/main/scala/org/apache/pekko/util/Collections.scala b/actor/src/main/scala/org/apache/pekko/util/Collections.scala index 12f9114959e..9311c3dadcd 100644 --- a/actor/src/main/scala/org/apache/pekko/util/Collections.scala +++ b/actor/src/main/scala/org/apache/pekko/util/Collections.scala @@ -58,8 +58,8 @@ private[pekko] object Collections { final def iterator: Iterator[To] = { val superIterator = valuesIterator new Iterator[To] { - private[this] var _next: To = _ - private[this] var _hasNext = false + private var _next: To = null.asInstanceOf[To] + private var _hasNext = false override final def hasNext: Boolean = { @tailrec def tailrecHasNext(): Boolean = { diff --git a/actor/src/main/scala/org/apache/pekko/util/ConstantFun.scala b/actor/src/main/scala/org/apache/pekko/util/ConstantFun.scala index 0a686df677f..87514df23b2 100644 --- a/actor/src/main/scala/org/apache/pekko/util/ConstantFun.scala +++ b/actor/src/main/scala/org/apache/pekko/util/ConstantFun.scala @@ -25,12 +25,12 @@ import pekko.japi.function.{ Function => JFun, Function2 => JFun2 } */ @InternalApi private[pekko] object ConstantFun { - private[this] val JavaIdentityFunction = new JFun[Any, Any] { + private val JavaIdentityFunction = new JFun[Any, Any] { @throws(classOf[Exception]) override def apply(param: Any): Any = param } - val JavaPairFunction = new JFun2[AnyRef, AnyRef, AnyRef JPair AnyRef] { - def apply(p1: AnyRef, p2: AnyRef): AnyRef JPair AnyRef = JPair(p1, p2) + val JavaPairFunction = new JFun2[AnyRef, AnyRef, JPair[AnyRef, AnyRef]] { + def apply(p1: AnyRef, p2: AnyRef): JPair[AnyRef, AnyRef] = JPair(p1, p2) } def javaCreatePairFunction[A, B]: JFun2[A, B, JPair[A, B]] = JavaPairFunction.asInstanceOf[JFun2[A, B, JPair[A, B]]] diff --git a/actor/src/main/scala/org/apache/pekko/util/DoubleLinkedList.scala b/actor/src/main/scala/org/apache/pekko/util/DoubleLinkedList.scala index bf2c79b22c1..cb56ba06b4a 100644 --- a/actor/src/main/scala/org/apache/pekko/util/DoubleLinkedList.scala +++ b/actor/src/main/scala/org/apache/pekko/util/DoubleLinkedList.scala @@ -29,8 +29,8 @@ private[pekko] final class DoubleLinkedList[Node]( setPrevious: (Node, OptionVal[Node]) => Unit, setNext: (Node, OptionVal[Node]) => Unit) { - private[this] var first: OptionVal[Node] = OptionVal.none - private[this] var last: OptionVal[Node] = OptionVal.none + private var first: OptionVal[Node] = OptionVal.none + private var last: OptionVal[Node] = OptionVal.none def isEmpty: Boolean = first.isEmpty @@ -138,7 +138,7 @@ private[pekko] final class DoubleLinkedList[Node]( private def iteratorFrom(start: OptionVal[Node], shift: Node => OptionVal[Node]): Iterator[Node] = new AbstractIterator[Node] { - private[this] var cursor: OptionVal[Node] = start + private var cursor: OptionVal[Node] = start override def hasNext: Boolean = cursor.isDefined override def next(): Node = { val node = cursor diff --git a/actor/src/main/scala/org/apache/pekko/util/FrequencySketch.scala b/actor/src/main/scala/org/apache/pekko/util/FrequencySketch.scala index f7c73393415..4f56d77811a 100644 --- a/actor/src/main/scala/org/apache/pekko/util/FrequencySketch.scala +++ b/actor/src/main/scala/org/apache/pekko/util/FrequencySketch.scala @@ -138,25 +138,25 @@ private[pekko] final class FrequencySketch[A]( private final val SlotBits = 64 - private[this] val counterWidth = counterBits - private[this] val slots = SlotBits / counterWidth - private[this] val rowWidth = math.max(1, width / slots) - private[this] val columnMask = width - 1 - private[this] val slotShift = FrequencySketch.Bits.powerOfTwoExponent(slots) - private[this] val slotMask = slots - 1 - private[this] val counterShift = FrequencySketch.Bits.powerOfTwoExponent(counterWidth) - private[this] val counterMask = if (counterBits == 64) Long.MaxValue else (1L << counterWidth) - 1 - - private[this] val oddMask = (1 to slots).foldLeft(1L)((mask, count) => mask | (1L << (count * counterWidth))) - - private[this] val resetMask = { + private val counterWidth = counterBits + private val slots = SlotBits / counterWidth + private val rowWidth = math.max(1, width / slots) + private val columnMask = width - 1 + private val slotShift = FrequencySketch.Bits.powerOfTwoExponent(slots) + private val slotMask = slots - 1 + private val counterShift = FrequencySketch.Bits.powerOfTwoExponent(counterWidth) + private val counterMask = if (counterBits == 64) Long.MaxValue else (1L << counterWidth) - 1 + + private val oddMask = (1 to slots).foldLeft(1L)((mask, count) => mask | (1L << (count * counterWidth))) + + private val resetMask = { val counterResetMask = counterMask >> 1 (1 to slots).foldLeft(counterResetMask)((mask, count) => mask | (counterResetMask << (count * counterWidth))) } - private[this] val matrix = Array.fill[Array[Long]](depth)(Array.ofDim[Long](rowWidth)) - private[this] val rowSizes = Array.ofDim[Int](depth) - private[this] var updatedSize = 0 + private val matrix = Array.fill[Array[Long]](depth)(Array.ofDim[Long](rowWidth)) + private val rowSizes = Array.ofDim[Int](depth) + private var updatedSize = 0 /** * Get the current size of the sketch (the number of incremented counters). @@ -300,12 +300,12 @@ private[pekko] final class FastFrequencySketch[A](width: Int, resetSize: Int) { private final val Seed2 = 0x9AE16A3B2F90404FL private final val Seed3 = 0xCBF29CE484222325L - private[this] val rowWidth = math.max(1, width >>> SlotShift) - private[this] val indexMask = width - 1 + private val rowWidth = math.max(1, width >>> SlotShift) + private val indexMask = width - 1 - private[this] val matrix = Array.fill[Array[Long]](Depth)(Array.ofDim[Long](rowWidth)) - private[this] val rowSizes = Array.ofDim[Int](Depth) - private[this] var updatedSize = 0 + private val matrix = Array.fill[Array[Long]](Depth)(Array.ofDim[Long](rowWidth)) + private val rowSizes = Array.ofDim[Int](Depth) + private var updatedSize = 0 def size: Int = updatedSize diff --git a/actor/src/main/scala/org/apache/pekko/util/ImmutableIntMap.scala b/actor/src/main/scala/org/apache/pekko/util/ImmutableIntMap.scala index d53b72296a5..8405e0fa075 100644 --- a/actor/src/main/scala/org/apache/pekko/util/ImmutableIntMap.scala +++ b/actor/src/main/scala/org/apache/pekko/util/ImmutableIntMap.scala @@ -41,7 +41,7 @@ import org.apache.pekko.annotation.InternalApi kvs(1) = value } - private[this] final def indexForKey(key: Int): Int = { + private final def indexForKey(key: Int): Int = { // Custom implementation of binary search since we encode key + value in consecutive indices. // We do the binary search on half the size of the array then project to the full size. // >>> 1 for division by 2: https://research.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html @@ -107,13 +107,13 @@ import org.apache.pekko.annotation.InternalApi } else insert(key, value, i) } else new ImmutableIntMap(key, value) - private[this] final def update(value: Int, valueIndex: Int): ImmutableIntMap = { + private final def update(value: Int, valueIndex: Int): ImmutableIntMap = { val newKvs = kvs.clone() // clone() can in theory be faster since it could do a malloc + memcpy iso. calloc etc newKvs(valueIndex) = value new ImmutableIntMap(newKvs, size) } - private[this] final def insert(key: Int, value: Int, index: Int): ImmutableIntMap = { + private final def insert(key: Int, value: Int, index: Int): ImmutableIntMap = { val at = ~index // ~n == -(n + 1): insert the entry at the right position—keep the array sorted val newKvs = new Array[Int](kvs.length + 2) System.arraycopy(kvs, 0, newKvs, 0, at) diff --git a/actor/src/main/scala/org/apache/pekko/util/LineNumbers.scala b/actor/src/main/scala/org/apache/pekko/util/LineNumbers.scala index 53b7668873f..424941490c1 100644 --- a/actor/src/main/scala/org/apache/pekko/util/LineNumbers.scala +++ b/actor/src/main/scala/org/apache/pekko/util/LineNumbers.scala @@ -358,7 +358,7 @@ object LineNumbers { private def readAttributes(d: DataInputStream)(implicit c: Constants): Option[String] = { val count = d.readUnsignedShort() if (debug) println(s"LNB: reading $count attributes") - if (c contains "SourceFile") { + if (c.contains("SourceFile")) { val s = c("SourceFile") val attributes = for (_ <- 1 to count) yield { diff --git a/actor/src/main/scala/org/apache/pekko/util/StablePriorityQueue.scala b/actor/src/main/scala/org/apache/pekko/util/StablePriorityQueue.scala index 594877e9e51..4bb863aa8de 100644 --- a/actor/src/main/scala/org/apache/pekko/util/StablePriorityQueue.scala +++ b/actor/src/main/scala/org/apache/pekko/util/StablePriorityQueue.scala @@ -38,7 +38,7 @@ trait PriorityQueueStabilizer[E <: AnyRef] extends AbstractQueue[E] { } override def iterator(): Iterator[E] = new Iterator[E] { - private[this] val backingIterator = backingQueue.iterator() + private val backingIterator = backingQueue.iterator() def hasNext: Boolean = backingIterator.hasNext def next(): E = backingIterator.next().element override def remove() = backingIterator.remove() diff --git a/actor/src/main/scala/org/apache/pekko/util/SubclassifiedIndex.scala b/actor/src/main/scala/org/apache/pekko/util/SubclassifiedIndex.scala index 256ff53c35c..477f386d1f0 100644 --- a/actor/src/main/scala/org/apache/pekko/util/SubclassifiedIndex.scala +++ b/actor/src/main/scala/org/apache/pekko/util/SubclassifiedIndex.scala @@ -71,7 +71,7 @@ private[pekko] object SubclassifiedIndex { } private[SubclassifiedIndex] def emptyMergeMap[K, V] = internalEmptyMergeMap.asInstanceOf[Map[K, Set[V]]] - private[this] val internalEmptyMergeMap = Map[AnyRef, Set[AnyRef]]().withDefaultValue(Set[AnyRef]()) + private val internalEmptyMergeMap = Map[AnyRef, Set[AnyRef]]().withDefaultValue(Set[AnyRef]()) } /** diff --git a/actor/src/main/scala/org/apache/pekko/util/TokenBucket.scala b/actor/src/main/scala/org/apache/pekko/util/TokenBucket.scala index a07a2866c85..e7fb53d98d3 100644 --- a/actor/src/main/scala/org/apache/pekko/util/TokenBucket.scala +++ b/actor/src/main/scala/org/apache/pekko/util/TokenBucket.scala @@ -20,8 +20,8 @@ private[pekko] abstract class TokenBucket(capacity: Long, nanosBetweenTokens: Lo require(capacity >= 0, "Capacity must be non-negative.") require(nanosBetweenTokens > 0, "Time between tokens must be larger than zero nanoseconds.") - private[this] var availableTokens: Long = _ - private[this] var lastUpdate: Long = _ + private var availableTokens: Long = 0L + private var lastUpdate: Long = 0L /** * This method must be called before the token bucket can be used. diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/ActorGraphInterpreterBoundaryBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/ActorGraphInterpreterBoundaryBenchmark.scala index 92b07b53ccc..cac3ea833e6 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/ActorGraphInterpreterBoundaryBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/ActorGraphInterpreterBoundaryBenchmark.scala @@ -29,9 +29,6 @@ import scala.concurrent.duration._ import org.openjdk.jmh.annotations._ import org.openjdk.jmh.annotations.OperationsPerInvocation import org.openjdk.jmh.infra.Blackhole -import org.reactivestreams.Publisher -import org.reactivestreams.Subscriber -import org.reactivestreams.Subscription import org.apache.pekko import pekko.actor.ActorSystem @@ -40,6 +37,10 @@ import pekko.stream.scaladsl.RunnableGraph import pekko.stream.scaladsl.Sink import pekko.stream.scaladsl.Source +import org.reactivestreams.Publisher +import org.reactivestreams.Subscriber +import org.reactivestreams.Subscription + import com.typesafe.config.ConfigFactory object ActorGraphInterpreterBoundaryBenchmark { @@ -51,8 +52,8 @@ object ActorGraphInterpreterBoundaryBenchmark { if (subscriber eq null) throw new NullPointerException("subscriber") subscriber.onSubscribe(new Subscription { - private[this] var cancelled = false - private[this] var index = 0 + private var cancelled = false + private var index = 0 override def request(n: Long): Unit = if (!cancelled) { @@ -83,9 +84,9 @@ object ActorGraphInterpreterBoundaryBenchmark { latch: CountDownLatch, cancelAfter: Int) extends Subscriber[MutableElement] { - private[this] var subscription: Subscription = _ - private[this] var seen = 0 - private[this] val failure = new AtomicReference[Throwable] + private var subscription: Subscription = _ + private var seen = 0 + private val failure = new AtomicReference[Throwable] override def onSubscribe(subscription: Subscription): Unit = { this.subscription = subscription diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/FusedGraphsBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/FusedGraphsBenchmark.scala index fd7425525f6..5fe66760606 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/FusedGraphsBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/FusedGraphsBenchmark.scala @@ -46,7 +46,7 @@ class TestSource(elems: Array[MutableElement]) extends GraphStage[SourceShape[Mu override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler { - private[this] var left = FusedGraphsBenchmark.ElementCount - 1 + private var left = FusedGraphsBenchmark.ElementCount - 1 override def onPull(): Unit = { if (left >= 0) { @@ -66,7 +66,7 @@ class JitSafeCompletionLatch extends GraphStageWithMaterializedValue[SinkShape[M override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, CountDownLatch) = { val latch = new CountDownLatch(1) val logic = new GraphStageLogic(shape) with InHandler { - private[this] var sum = 0 + private var sum = 0 override def preStart(): Unit = pull(in) override def onPush(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/GraphStageConstructionBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/GraphStageConstructionBenchmark.scala index fb2aa9a9637..efa220f2960 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/GraphStageConstructionBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/GraphStageConstructionBenchmark.scala @@ -22,6 +22,14 @@ import java.util.concurrent.TimeUnit import scala.collection.immutable import scala.concurrent.Promise +import org.openjdk.jmh.annotations.Benchmark +import org.openjdk.jmh.annotations.BenchmarkMode +import org.openjdk.jmh.annotations.Mode +import org.openjdk.jmh.annotations.OutputTimeUnit +import org.openjdk.jmh.annotations.Scope +import org.openjdk.jmh.annotations.State +import org.openjdk.jmh.infra.Blackhole + import org.apache.pekko.NotUsed import org.apache.pekko.stream.impl.LinearTraversalBuilder import org.apache.pekko.stream.impl.Stages.DefaultAttributes @@ -32,13 +40,6 @@ import org.apache.pekko.stream.scaladsl.Keep import org.apache.pekko.stream.scaladsl.Sink import org.apache.pekko.stream.scaladsl.Source import org.apache.pekko.stream.stage.GraphStageWithMaterializedValue -import org.openjdk.jmh.annotations.Benchmark -import org.openjdk.jmh.annotations.BenchmarkMode -import org.openjdk.jmh.annotations.Mode -import org.openjdk.jmh.annotations.OutputTimeUnit -import org.openjdk.jmh.annotations.Scope -import org.openjdk.jmh.annotations.State -import org.openjdk.jmh.infra.Blackhole @State(Scope.Benchmark) @BenchmarkMode(Array(Mode.Throughput)) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/RangeSourceBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/RangeSourceBenchmark.scala index 59925f9612d..eb53966012b 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/RangeSourceBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/RangeSourceBenchmark.scala @@ -42,7 +42,7 @@ final class IntCompletionLatch extends GraphStageWithMaterializedValue[SinkShape override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, CountDownLatch) = { val latch = new CountDownLatch(1) val logic = new GraphStageLogic(shape) with InHandler { - private[this] var sum = 0 + private var sum = 0 override def preStart(): Unit = pull(in) override def onPush(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/io/TlsBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/io/TlsBenchmark.scala index e02ee3ada9b..64968581df5 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/io/TlsBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/io/TlsBenchmark.scala @@ -25,7 +25,6 @@ import scala.concurrent.Await import scala.concurrent.duration._ import scala.util.{ Success, Try } -import com.typesafe.config.{ Config, ConfigFactory } import org.openjdk.jmh.annotations._ import org.apache.pekko @@ -37,6 +36,8 @@ import pekko.stream.impl.io.{ TlsGraphStage, TlsModule } import pekko.stream.scaladsl._ import pekko.util.ByteString +import com.typesafe.config.{ Config, ConfigFactory } + /** * JMH benchmark comparing the legacy actor-based TLS path (`TlsModule`) to the * GraphStage path (`TlsGraphStage`). diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteStringParser_readNum_Benchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteStringParser_readNum_Benchmark.scala index a018c109809..6df3f7a1e84 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteStringParser_readNum_Benchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteStringParser_readNum_Benchmark.scala @@ -19,11 +19,11 @@ package org.apache.pekko.util import java.util.concurrent.TimeUnit +import org.openjdk.jmh.annotations._ + import org.apache.pekko import pekko.stream.impl.io.ByteStringParser -import org.openjdk.jmh.annotations._ - @State(Scope.Benchmark) @Measurement(timeUnit = TimeUnit.MILLISECONDS) class ByteStringParser_readNum_Benchmark { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/FastFrequencySketchBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/FastFrequencySketchBenchmark.scala index 3dd27b0a6ca..38f6ed4d730 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/FastFrequencySketchBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/FastFrequencySketchBenchmark.scala @@ -28,13 +28,13 @@ import org.openjdk.jmh.annotations.Warmup @Warmup(iterations = 3, time = 20, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 3, time = 10, timeUnit = TimeUnit.SECONDS) class FastFrequencySketchBenchmark { - private[this] val Capacity = 10000 - private[this] val GeneratedSize = 1 << 16 + private val Capacity = 10000 + private val GeneratedSize = 1 << 16 private final val IndexMask = 0xFFFF - private[this] var sketch: FastFrequencySketch[String] = _ - private[this] var generated: Array[String] = _ - private[this] var index: Int = 0 + private var sketch: FastFrequencySketch[String] = _ + private var generated: Array[String] = _ + private var index: Int = 0 @Setup def setup(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/FrequencySketchBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/FrequencySketchBenchmark.scala index a92b0defdd7..f89bdd9b181 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/FrequencySketchBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/FrequencySketchBenchmark.scala @@ -28,13 +28,13 @@ import org.openjdk.jmh.annotations.Warmup @Warmup(iterations = 3, time = 20, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 3, time = 10, timeUnit = TimeUnit.SECONDS) class FrequencySketchBenchmark { - private[this] val Capacity = 10000 - private[this] val GeneratedSize = 1 << 16 + private val Capacity = 10000 + private val GeneratedSize = 1 << 16 private final val IndexMask = 0xFFFF - private[this] var sketch: FrequencySketch[String] = _ - private[this] var generated: Array[String] = _ - private[this] var index: Int = 0 + private var sketch: FrequencySketch[String] = _ + private var generated: Array[String] = _ + private var index: Int = 0 @Setup def setup(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/ImmutableIntMapBench.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/ImmutableIntMapBench.scala index 6e385202fe3..fc3779f6b36 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/ImmutableIntMapBench.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/ImmutableIntMapBench.scala @@ -27,33 +27,33 @@ import org.openjdk.jmh.annotations._ @Measurement(iterations = 10, time = 15, timeUnit = TimeUnit.MICROSECONDS, batchSize = 1) class ImmutableIntMapBench { - @tailrec private[this] final def add(n: Int, c: ImmutableIntMap = ImmutableIntMap.empty): ImmutableIntMap = + @tailrec private final def add(n: Int, c: ImmutableIntMap = ImmutableIntMap.empty): ImmutableIntMap = if (n >= 0) add(n - 1, c.updated(n, n)) else c - @tailrec private[this] final def contains(n: Int, by: Int, to: Int, in: ImmutableIntMap, b: Boolean): Boolean = + @tailrec private final def contains(n: Int, by: Int, to: Int, in: ImmutableIntMap, b: Boolean): Boolean = if (n <= to) { val result = in.contains(n) contains(n + by, by, to, in, result) } else b - @tailrec private[this] final def get(n: Int, by: Int, to: Int, in: ImmutableIntMap, b: Int): Int = + @tailrec private final def get(n: Int, by: Int, to: Int, in: ImmutableIntMap, b: Int): Int = if (n <= to) { val result = in.get(n) get(n + by, by, to, in, result) } else b - @tailrec private[this] final def hashCode(n: Int, in: ImmutableIntMap, b: Int): Int = + @tailrec private final def hashCode(n: Int, in: ImmutableIntMap, b: Int): Int = if (n >= 0) { val result = in.hashCode hashCode(n - 1, in, result) } else b - @tailrec private[this] final def updateIfAbsent(n: Int, by: Int, to: Int, in: ImmutableIntMap): ImmutableIntMap = + @tailrec private final def updateIfAbsent(n: Int, by: Int, to: Int, in: ImmutableIntMap): ImmutableIntMap = if (n <= to) updateIfAbsent(n + by, by, to, in.updateIfAbsent(n, n)) else in - @tailrec private[this] final def getKey(iterations: Int, key: Int, from: ImmutableIntMap): ImmutableIntMap = { + @tailrec private final def getKey(iterations: Int, key: Int, from: ImmutableIntMap): ImmutableIntMap = { if (iterations > 0 && key != Int.MinValue) { val k = from.get(key) getKey(iterations - 1, k, from) diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingProducerController.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingProducerController.scala index 342ecf2b29c..4266c16011c 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingProducerController.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingProducerController.scala @@ -285,7 +285,8 @@ object ShardingProducerController { producerId: String, region: ActorRef[ShardingEnvelope[ConsumerController.SequencedMessage[A]]], durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { - apply(producerId, region, durableQueueBehavior.toScala)(ClassTag(messageClass)) + implicit val ct: ClassTag[A] = ClassTag(messageClass) + apply(producerId, region, durableQueueBehavior.toScala) } /** @@ -297,7 +298,8 @@ object ShardingProducerController { region: ActorRef[ShardingEnvelope[ConsumerController.SequencedMessage[A]]], durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]], settings: Settings): Behavior[Command[A]] = { - apply(producerId, region, durableQueueBehavior.toScala, settings)(ClassTag(messageClass)) + implicit val ct: ClassTag[A] = ClassTag(messageClass) + apply(producerId, region, durableQueueBehavior.toScala, settings) } // TODO maybe there is a need for variant taking message extractor instead of ShardingEnvelope diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ClusterShardingImpl.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ClusterShardingImpl.scala index 98406919d64..df01f21032c 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ClusterShardingImpl.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ClusterShardingImpl.scala @@ -361,7 +361,7 @@ import pekko.util.{ ByteString, Timeout } import pekko.actor.typed.internal.{ adapter => adapt } // Note: _promiseRef mustn't have a type pattern, since it can be null - private[this] val (_ref: ActorRef[U], _future: Future[U], _promiseRef) = + private val (_ref: ActorRef[U], _future: Future[U], _promiseRef) = if (classic.isTerminated) ( adapt.ActorRefAdapter[U](classic.provider.deadLetters), diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessImpl.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessImpl.scala index fb69fe2a8e3..50ef440a899 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessImpl.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessImpl.scala @@ -62,12 +62,11 @@ private[pekko] final class ShardedDaemonProcessImpl(system: ActorSystem[?]) def init[T](name: String, numberOfInstances: Int, behaviorFactory: Int => Behavior[T])( implicit classTag: ClassTag[T]): Unit = - init(name, numberOfInstances, behaviorFactory, ShardedDaemonProcessSettings(system), None, None)(classTag) + init(name, numberOfInstances, behaviorFactory, ShardedDaemonProcessSettings(system), None, None) override def init[T](name: String, numberOfInstances: Int, behaviorFactory: Int => Behavior[T], stopMessage: T)( implicit classTag: ClassTag[T]): Unit = - init(name, numberOfInstances, behaviorFactory, ShardedDaemonProcessSettings(system), Some(stopMessage), None)( - classTag) + init(name, numberOfInstances, behaviorFactory, ShardedDaemonProcessSettings(system), Some(stopMessage), None) override def init[T]( name: String, @@ -214,22 +213,26 @@ private[pekko] final class ShardedDaemonProcessImpl(system: ActorSystem[?]) messageClass: Class[T], name: String, numberOfInstances: Int, - behaviorFactory: IntFunction[Behavior[T]]): Unit = - init(name, numberOfInstances, n => behaviorFactory(n))(ClassTag(messageClass)) + behaviorFactory: IntFunction[Behavior[T]]): Unit = { + implicit val ct: ClassTag[T] = ClassTag(messageClass) + init(name, numberOfInstances, n => behaviorFactory(n)) + } override def init[T]( messageClass: Class[T], name: String, numberOfInstances: Int, behaviorFactory: IntFunction[Behavior[T]], - stopMessage: T): Unit = + stopMessage: T): Unit = { + implicit val ct: ClassTag[T] = ClassTag(messageClass) init( name, numberOfInstances, n => behaviorFactory(n), ShardedDaemonProcessSettings(system), Some(stopMessage), - None)(ClassTag(messageClass)) + None) + } override def init[T]( messageClass: Class[T], @@ -237,8 +240,10 @@ private[pekko] final class ShardedDaemonProcessImpl(system: ActorSystem[?]) numberOfInstances: Int, behaviorFactory: IntFunction[Behavior[T]], settings: ShardedDaemonProcessSettings, - stopMessage: Optional[T]): Unit = - init(name, numberOfInstances, n => behaviorFactory(n), settings, stopMessage.toScala, None)(ClassTag(messageClass)) + stopMessage: Optional[T]): Unit = { + implicit val ct: ClassTag[T] = ClassTag(messageClass) + init(name, numberOfInstances, n => behaviorFactory(n), settings, stopMessage.toScala, None) + } override def init[T]( messageClass: Class[T], @@ -247,14 +252,16 @@ private[pekko] final class ShardedDaemonProcessImpl(system: ActorSystem[?]) behaviorFactory: IntFunction[Behavior[T]], settings: ShardedDaemonProcessSettings, stopMessage: Optional[T], - shardAllocationStrategy: Optional[ShardAllocationStrategy]): Unit = + shardAllocationStrategy: Optional[ShardAllocationStrategy]): Unit = { + implicit val ct: ClassTag[T] = ClassTag(messageClass) init( name, numberOfInstances, n => behaviorFactory(n), settings, stopMessage.toScala, - shardAllocationStrategy.toScala)(ClassTag(messageClass)) + shardAllocationStrategy.toScala) + } override def initWithContext[T]( messageClass: Class[T], @@ -262,8 +269,8 @@ private[pekko] final class ShardedDaemonProcessImpl(system: ActorSystem[?]) initialNumberOfInstances: Int, behaviorFactory: java.util.function.Function[ShardedDaemonProcessContext, Behavior[T]]) : ActorRef[ShardedDaemonProcessCommand] = { - val classTag = ClassTag[T](messageClass) - internalInitWithContext[T](name, initialNumberOfInstances, behaviorFactory.apply, None, None, None, true)(classTag) + implicit val classTag: ClassTag[T] = ClassTag[T](messageClass) + internalInitWithContext[T](name, initialNumberOfInstances, behaviorFactory.apply, None, None, None, true) } override def initWithContext[T]( @@ -290,7 +297,7 @@ private[pekko] final class ShardedDaemonProcessImpl(system: ActorSystem[?]) settings: ShardedDaemonProcessSettings, stopMessage: Optional[T], shardAllocationStrategy: Optional[ShardAllocationStrategy]): ActorRef[ShardedDaemonProcessCommand] = { - val classTag = ClassTag[T](messageClass) + implicit val classTag: ClassTag[T] = ClassTag[T](messageClass) internalInitWithContext( name, initialNumberOfInstances, @@ -298,6 +305,6 @@ private[pekko] final class ShardedDaemonProcessImpl(system: ActorSystem[?]) Some(settings), stopMessage.toScala, shardAllocationStrategy.toScala, - supportsRescale = true)(classTag) + supportsRescale = true) } } diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/javadsl/ShardedDaemonProcess.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/javadsl/ShardedDaemonProcess.scala index e7e48ed9ce5..32f63beb801 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/javadsl/ShardedDaemonProcess.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/javadsl/ShardedDaemonProcess.scala @@ -14,8 +14,8 @@ package org.apache.pekko.cluster.sharding.typed.javadsl import java.util.Optional -import java.util.function.IntFunction import java.util.function.{ Function => JFunction } +import java.util.function.IntFunction import org.apache.pekko import pekko.actor.typed.ActorRef diff --git a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessIdSpec.scala b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessIdSpec.scala index f7f4d1fdd64..bedfc268403 100644 --- a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessIdSpec.scala +++ b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessIdSpec.scala @@ -14,6 +14,7 @@ package org.apache.pekko.cluster.sharding.typed.internal import org.apache.pekko.cluster.sharding.typed.internal.ShardedDaemonProcessId.DecodedId + import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardRegion.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardRegion.scala index ca59e57c912..aa81643285a 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardRegion.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardRegion.scala @@ -638,7 +638,10 @@ private[pekko] class ShardRegion( // sort by age, oldest first val ageOrdering = Member.ageOrdering // membersByAge is only used for tracking where coordinator is running - var membersByAge: immutable.SortedSet[Member] = immutable.SortedSet.empty(ageOrdering) + var membersByAge: immutable.SortedSet[Member] = { + implicit val ord: Ordering[Member] = ageOrdering + immutable.SortedSet.empty[Member] + } // membersByAge contains members with these status private val memberStatusOfInterest: Set[MemberStatus] = Set(MemberStatus.Up, MemberStatus.Leaving, MemberStatus.Exiting) @@ -772,9 +775,10 @@ private[pekko] class ShardRegion( } def receiveClusterState(state: CurrentClusterState): Unit = { + implicit val ord: Ordering[Member] = ageOrdering changeMembers( immutable.SortedSet - .empty(ageOrdering) + .empty[Member] .union(state.members.filter(m => memberStatusOfInterest(m.status) && matchingCoordinatorRole(m)))) } diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingCoordinatorRoleSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingCoordinatorRoleSpec.scala index d1bb7c545b8..e4fd8737ac4 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingCoordinatorRoleSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingCoordinatorRoleSpec.scala @@ -15,9 +15,6 @@ package org.apache.pekko.cluster.sharding import scala.concurrent.duration._ -import com.typesafe.config.Config -import com.typesafe.config.ConfigFactory - import org.apache.pekko import pekko.actor.ActorRef import pekko.actor.PoisonPill @@ -25,6 +22,9 @@ import pekko.actor.Props import pekko.cluster.sharding.MultiNodeClusterShardingSpec.EntityActor import pekko.testkit._ +import com.typesafe.config.Config +import com.typesafe.config.ConfigFactory + class ClusterShardingCoordinatorRoleSpecConfig( mode: String, rememberEntities: Boolean, diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesAndStartEntitySpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesAndStartEntitySpec.scala index 330961469dc..431537c964e 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesAndStartEntitySpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesAndStartEntitySpec.scala @@ -13,6 +13,8 @@ package org.apache.pekko.cluster.sharding +import scala.concurrent.duration._ + import org.apache.pekko import pekko.actor.Actor import pekko.actor.ActorRef @@ -30,7 +32,6 @@ import pekko.testkit.WithLogCapturing import org.scalatest.wordspec.AnyWordSpecLike -import scala.concurrent.duration._ import com.typesafe.config.ConfigFactory object RememberEntitiesAndStartEntitySpec { diff --git a/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManager.scala b/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManager.scala index 0fca6107e39..6727f883aa4 100644 --- a/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManager.scala +++ b/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManager.scala @@ -297,7 +297,10 @@ object ClusterSingletonManager { val cluster = Cluster(context.system) // sort by age, oldest first val ageOrdering = Member.ageOrdering - var membersByAge: immutable.SortedSet[Member] = immutable.SortedSet.empty(ageOrdering) + var membersByAge: immutable.SortedSet[Member] = { + implicit val ord: Ordering[Member] = ageOrdering + immutable.SortedSet.empty[Member] + } var changes = Vector.empty[AnyRef] @@ -337,8 +340,9 @@ object ClusterSingletonManager { def handleInitial(state: CurrentClusterState): Unit = { // all members except Joining and WeaklyUp + implicit val ord: Ordering[Member] = ageOrdering membersByAge = immutable.SortedSet - .empty(ageOrdering) + .empty[Member] .union(state.members.filter(m => m.upNumber != Int.MaxValue && matchingRole(m))) // If there is some removal in progress of an older node it's not safe to immediately become oldest, diff --git a/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonProxy.scala b/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonProxy.scala index d1d2607395b..ba001c38a41 100644 --- a/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonProxy.scala +++ b/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonProxy.scala @@ -182,7 +182,10 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste var singleton: Option[ActorRef] = None // sort by age, oldest first val ageOrdering = Member.ageOrdering - var membersByAge: immutable.SortedSet[Member] = immutable.SortedSet.empty(ageOrdering) + var membersByAge: immutable.SortedSet[Member] = { + implicit val ord: Ordering[Member] = ageOrdering + immutable.SortedSet.empty[Member] + } var buffer: MessageBuffer = MessageBuffer.empty @@ -212,8 +215,9 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste def handleInitial(state: CurrentClusterState): Unit = { trackChange { () => + implicit val ord: Ordering[Member] = ageOrdering membersByAge = immutable.SortedSet - .empty(ageOrdering) + .empty[Member] .union(state.members.collect { case m if m.status == MemberStatus.Up && matchingRole(m) => m }) diff --git a/cluster-typed/src/main/scala-3/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionistProtocol.scala b/cluster-typed/src/main/scala-3/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionistProtocol.scala index de934f487ee..5fda7dbf49c 100644 --- a/cluster-typed/src/main/scala-3/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionistProtocol.scala +++ b/cluster-typed/src/main/scala-3/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionistProtocol.scala @@ -25,7 +25,7 @@ import pekko.annotation.InternalApi private[receptionist] object ClusterReceptionistProtocol { type Aux[P] = AbstractServiceKey { type Protocol = P } - type SubscriptionsKV[K <: Aux[_]] = K match { + type SubscriptionsKV[K <: Aux[?]] = K match { case Aux[t] => ActorRef[ReceptionistMessages.Listing[t]] } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/CrossDcClusterHeartbeat.scala b/cluster/src/main/scala/org/apache/pekko/cluster/CrossDcClusterHeartbeat.scala index 2d6ba5a23a0..fde60828f0f 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/CrossDcClusterHeartbeat.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/CrossDcClusterHeartbeat.scala @@ -333,7 +333,10 @@ private[cluster] final case class CrossDcHeartbeatingState( private[cluster] object CrossDcHeartbeatingState { /** Sorted by age */ - private def emptyMembersSortedSet: immutable.SortedSet[Member] = immutable.SortedSet.empty[Member](Member.ageOrdering) + private def emptyMembersSortedSet: immutable.SortedSet[Member] = { + implicit val ord: Ordering[Member] = Member.ageOrdering + immutable.SortedSet.empty[Member] + } // Since we need ordering of oldests guaranteed, we must only look at Up (or Leaving, Exiting...) nodes def atLeastInUpState(m: Member): Boolean = @@ -356,7 +359,8 @@ private[cluster] object CrossDcHeartbeatingState { // we need to enforce the ageOrdering for the SortedSet in each DC groupedByDc.map { case (dc, ms) => - dc -> immutable.SortedSet.empty[Member](Member.ageOrdering).union(ms) + implicit val ord: Ordering[Member] = Member.ageOrdering + dc -> immutable.SortedSet.empty[Member].union(ms) } } }) diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/MembershipState.scala b/cluster/src/main/scala/org/apache/pekko/cluster/MembershipState.scala index 2a56bbeb3d6..02662adf0d4 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/MembershipState.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/MembershipState.scala @@ -128,6 +128,7 @@ import pekko.cluster.MemberStatus._ * @return Up to `crossDcConnections` oldest members for each DC */ lazy val ageSortedTopOldestMembersPerDc: Map[DataCenter, immutable.SortedSet[Member]] = { + implicit val ord: Ordering[Member] = Member.ageOrdering latestGossip.members.foldLeft(Map.empty[DataCenter, immutable.SortedSet[Member]]) { (acc, member) => acc.get(member.dataCenter) match { case Some(set) => @@ -141,7 +142,7 @@ import pekko.cluster.MemberStatus._ } } case None => - acc + (member.dataCenter -> (immutable.SortedSet.empty(Member.ageOrdering) + member)) + acc + (member.dataCenter -> (immutable.SortedSet.empty[Member] + member)) } } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/Reachability.scala b/cluster/src/main/scala/org/apache/pekko/cluster/Reachability.scala index 3df1f913f94..c2816da4f99 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/Reachability.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/Reachability.scala @@ -28,8 +28,8 @@ private[cluster] object Reachability { new Reachability(records, versions) def create(records: immutable.Seq[Record], versions: Map[UniqueAddress, Long]): Reachability = records match { - case r: immutable.IndexedSeq[Record] => apply(r, versions) - case _ => apply(records.toVector, versions) + case r: (immutable.IndexedSeq[Record] @unchecked) => apply(r, versions) + case _ => apply(records.toVector, versions) } @SerialVersionUID(1L) diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/sbr/DowningStrategy.scala b/cluster/src/main/scala/org/apache/pekko/cluster/sbr/DowningStrategy.scala index ccc209d5e2c..8f781cb27e3 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/sbr/DowningStrategy.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/sbr/DowningStrategy.scala @@ -85,7 +85,10 @@ import pekko.coordination.lease.scaladsl.Lease protected def ordering: Ordering[Member] = Member.ordering // all members in self DC, both joining and up. - private var _allMembers: immutable.SortedSet[Member] = immutable.SortedSet.empty(ordering) + private var _allMembers: immutable.SortedSet[Member] = { + implicit val ord: Ordering[Member] = ordering + immutable.SortedSet.empty[Member] + } def role: Option[String] diff --git a/discovery/src/main/scala/org/apache/pekko/discovery/ServiceDiscovery.scala b/discovery/src/main/scala/org/apache/pekko/discovery/ServiceDiscovery.scala index 9f372b67c46..a6eeda88305 100644 --- a/discovery/src/main/scala/org/apache/pekko/discovery/ServiceDiscovery.scala +++ b/discovery/src/main/scala/org/apache/pekko/discovery/ServiceDiscovery.scala @@ -21,9 +21,10 @@ import java.util.concurrent.TimeUnit import scala.collection.immutable import scala.concurrent.Future import scala.concurrent.duration.FiniteDuration -import scala.jdk.OptionConverters._ import scala.jdk.DurationConverters._ import scala.jdk.FutureConverters._ +import scala.jdk.OptionConverters._ + import org.apache.pekko import pekko.actor.{ DeadLetterSuppression, NoSerializationVerificationNeeded } import pekko.util.HashCode diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/Replicator.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/Replicator.scala index 37f622c2ce5..35393c4cb74 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/Replicator.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/Replicator.scala @@ -1374,7 +1374,10 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog // cluster members sorted by age, oldest first,, doesn't contain selfAddress, doesn't contain joining and weaklyUp // only used when prefer-oldest is enabled - var membersByAge: immutable.SortedSet[Member] = immutable.SortedSet.empty(Member.ageOrdering) + var membersByAge: immutable.SortedSet[Member] = { + implicit val ord: Ordering[Member] = Member.ageOrdering + immutable.SortedSet.empty[Member] + } // cluster weaklyUp nodes, doesn't contain selfAddress var weaklyUpNodes: immutable.SortedSet[UniqueAddress] = immutable.SortedSet.empty @@ -1393,7 +1396,10 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog var removedNodes: Map[UniqueAddress, Long] = Map.empty // all nodes sorted with the leader first - var leader: TreeSet[Member] = TreeSet.empty(Member.leaderStatusOrdering) + var leader: TreeSet[Member] = { + implicit val ord: Ordering[Member] = Member.leaderStatusOrdering + TreeSet.empty[Member] + } def isLeader: Boolean = leader.nonEmpty && leader.head.address == selfAddress && leader.head.status == MemberStatus.Up diff --git a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/WildcardSubscribeSpec.scala b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/WildcardSubscribeSpec.scala index 82caf3c2163..a5c115f52fa 100644 --- a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/WildcardSubscribeSpec.scala +++ b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/WildcardSubscribeSpec.scala @@ -15,14 +15,14 @@ package org.apache.pekko.cluster.ddata import scala.concurrent.duration._ -import com.typesafe.config.ConfigFactory - import org.apache.pekko.cluster.Cluster import org.apache.pekko.remote.testconductor.RoleName import org.apache.pekko.remote.testkit.MultiNodeConfig import org.apache.pekko.remote.testkit.MultiNodeSpec import org.apache.pekko.testkit._ +import com.typesafe.config.ConfigFactory + object WildcardSubscribeSpec extends MultiNodeConfig { val first = role("first") val second = role("second") @@ -45,8 +45,8 @@ class WildcardSubscribeSpecMultiJvmNode1 extends WildcardSubscribeSpec class WildcardSubscribeSpecMultiJvmNode2 extends WildcardSubscribeSpec class WildcardSubscribeSpec extends MultiNodeSpec(WildcardSubscribeSpec) with STMultiNodeSpec with ImplicitSender { - import WildcardSubscribeSpec._ import Replicator._ + import WildcardSubscribeSpec._ override def initialParticipants: Int = roles.size diff --git a/docs/src/main/paradox/stream/operators/index.md b/docs/src/main/paradox/stream/operators/index.md index f39c251bb8f..011a1e1cf76 100644 --- a/docs/src/main/paradox/stream/operators/index.md +++ b/docs/src/main/paradox/stream/operators/index.md @@ -121,7 +121,7 @@ For example, following snippet will fall with timeout exception: |StreamConverters|@ref[fromInputStream](StreamConverters/fromInputStream.md)|Create a source that wraps an `InputStream`.| |StreamConverters|@ref[fromJavaStream](StreamConverters/fromJavaStream.md)|Create a source that wraps a Java 8 `java.util.stream.Stream`.| |StreamConverters|@ref[fromOutputStream](StreamConverters/fromOutputStream.md)|Create a sink that wraps an `OutputStream`.| -|StreamConverters|@ref[javaCollector](StreamConverters/javaCollector.md)|Create a sink which materializes into a @scala[`Future`] @java[`CompletionStage`] which will be completed with a result of the Java 8 `Collector` transformation and reduction operations.| +|StreamConverters|@ref[javaCollector](StreamConverters/javaCollector.md)|Create a sink which materializes into a @scala[`Future`] @java[`CompletionStage`] which will be completed with a result of the Java `Collector` transformation and reduction operations.| |StreamConverters|@ref[javaCollectorParallelUnordered](StreamConverters/javaCollectorParallelUnordered.md)|Create a sink which materializes into a @scala[`Future`] @java[`CompletionStage`] which will be completed with a result of the Java 8 `Collector` transformation and reduction operations.| ## File IO Sinks and Sources diff --git a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/MultiNodeSpec.scala b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/MultiNodeSpec.scala index a9dd7f0e6d1..cb14584c5e0 100644 --- a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/MultiNodeSpec.scala +++ b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/MultiNodeSpec.scala @@ -342,7 +342,7 @@ abstract class MultiNodeSpec( } }) - val log: LoggingAdapter = Logging(system, this)(_.getClass.getName) + val log: LoggingAdapter = Logging(system, classOf[MultiNodeSpec]) /** * Enrich `.await()` onto all Awaitables, using remaining duration from the innermost diff --git a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/typed/EventEnvelope.scala b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/typed/EventEnvelope.scala index db828201dea..6cbb7e53355 100644 --- a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/typed/EventEnvelope.scala +++ b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/typed/EventEnvelope.scala @@ -13,8 +13,8 @@ package org.apache.pekko.persistence.query.typed -import java.util.Optional import java.util.{ Set => JSet } +import java.util.Optional import org.apache.pekko import pekko.annotation.ApiMayChange diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/SnapshotStorage.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/SnapshotStorage.scala index 438a9df6876..6258688da57 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/SnapshotStorage.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/SnapshotStorage.scala @@ -13,8 +13,6 @@ package org.apache.pekko.persistence.testkit -import scala.util.Success - import org.apache.pekko import pekko.actor.Extension import pekko.annotation.InternalApi @@ -42,7 +40,6 @@ private[testkit] trait SnapshotStorage WriteSnapshot(SnapshotMeta(meta.sequenceNr, meta.timestamp), payload)) match { case ProcessingSuccess => add(meta.persistenceId, (meta, payload)) - Success(()) case f: ProcessingFailure => throw f.error } diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/EventSourcedBehaviorTestKit.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/EventSourcedBehaviorTestKit.scala index 3695c8ef304..f99316a4dd9 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/EventSourcedBehaviorTestKit.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/EventSourcedBehaviorTestKit.scala @@ -161,8 +161,10 @@ object EventSourcedBehaviorTestKit { * The first event as a given expected type. It will throw `AssertionError` if there is no event or * if the event is of a different type. */ - def eventOfType[E <: Event](eventClass: Class[E]): E = - delegate.eventOfType(ClassTag[E](eventClass)) + def eventOfType[E <: Event](eventClass: Class[E]): E = { + implicit val ct: ClassTag[E] = ClassTag(eventClass) + delegate.eventOfType[E] + } /** * The state after applying the events. @@ -173,8 +175,10 @@ object EventSourcedBehaviorTestKit { /** * The state as a given expected type. It will throw `AssertionError` if the state is of a different type. */ - def stateOfType[S <: State](stateClass: Class[S]): S = - delegate.stateOfType(ClassTag[S](stateClass)) + def stateOfType[S <: State](stateClass: Class[S]): S = { + implicit val ct: ClassTag[S] = ClassTag(stateClass) + delegate.stateOfType[S] + } } /** @@ -195,8 +199,10 @@ object EventSourcedBehaviorTestKit { * The reply as a given expected type. It will throw `AssertionError` if there is no reply or * if the reply is of a different type. */ - def replyOfType[R <: Reply](replyClass: Class[R]): R = - delegate.replyOfType(ClassTag[R](replyClass)) + def replyOfType[R <: Reply](replyClass: Class[R]): R = { + implicit val ct: ClassTag[R] = ClassTag(replyClass) + delegate.replyOfType[R] + } /** * `true` if there is no reply. diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/PersistenceProbeBehavior.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/PersistenceProbeBehavior.scala index 1d5898d8ee9..b459142cb97 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/PersistenceProbeBehavior.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/PersistenceProbeBehavior.scala @@ -17,12 +17,13 @@ import java.util.{ List, Set } import scala.collection.immutable.{ Set => ScalaSet } +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.actor.testkit.typed.javadsl.BehaviorTestKit import pekko.actor.typed.Behavior import pekko.annotation.DoNotInherit import pekko.persistence.testkit.internal.PersistenceProbeImpl -import org.jspecify.annotations.Nullable /** * Factory methods to create PersistenceProbeBehavior instances for testing. diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/scaladsl/PersistenceTestKitReadJournal.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/scaladsl/PersistenceTestKitReadJournal.scala index 4d7d6e8e705..cfd08ebf980 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/scaladsl/PersistenceTestKitReadJournal.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/scaladsl/PersistenceTestKitReadJournal.scala @@ -14,6 +14,7 @@ package org.apache.pekko.persistence.testkit.query.scaladsl import java.time.Instant import java.time.temporal.ChronoUnit + import scala.annotation.nowarn import scala.collection.immutable diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorRetentionOnlyOneSnapshotSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorRetentionOnlyOneSnapshotSpec.scala index 7d3bd63743c..c814e483835 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorRetentionOnlyOneSnapshotSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorRetentionOnlyOneSnapshotSpec.scala @@ -18,9 +18,6 @@ import java.util.concurrent.atomic.AtomicInteger import scala.util.Success import scala.util.Try -import com.typesafe.config.ConfigFactory -import org.scalatest.wordspec.AnyWordSpecLike - import org.apache.pekko import pekko.actor.testkit.typed.scaladsl._ import pekko.actor.typed.scaladsl.Behaviors @@ -30,6 +27,10 @@ import pekko.persistence.typed.DeleteEventsCompleted import pekko.persistence.typed.EventSourcedSignal import pekko.persistence.typed.PersistenceId +import org.scalatest.wordspec.AnyWordSpecLike + +import com.typesafe.config.ConfigFactory + object EventSourcedBehaviorRetentionOnlyOneSnapshotSpec { private val config = ConfigFactory.parseString(s""" ${PersistenceTestKitSnapshotPlugin.PluginId} { diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventSourcedBehavior.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventSourcedBehavior.scala index a653d242785..3e4d61b9b3c 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventSourcedBehavior.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventSourcedBehavior.scala @@ -19,6 +19,8 @@ import java.util.Optional import scala.annotation.nowarn import scala.jdk.OptionConverters._ +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.actor.typed import pekko.actor.typed.BackoffSupervisorStrategy @@ -31,7 +33,6 @@ import pekko.persistence.typed.EventAdapter import pekko.persistence.typed.internal._ import com.typesafe.config.Config -import org.jspecify.annotations.Nullable abstract class EventSourcedBehavior[Command, Event, State] private[pekko] ( val persistenceId: PersistenceId, diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/DurableStateBehavior.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/DurableStateBehavior.scala index 54b3b6003af..4bb33e52f29 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/DurableStateBehavior.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/DurableStateBehavior.scala @@ -15,6 +15,8 @@ package org.apache.pekko.persistence.typed.state.javadsl import java.util.Optional +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.actor.typed import pekko.actor.typed.BackoffSupervisorStrategy @@ -28,7 +30,6 @@ import pekko.persistence.typed.SnapshotAdapter import pekko.persistence.typed.state.internal import pekko.persistence.typed.state.internal._ import pekko.persistence.typed.state.scaladsl -import org.jspecify.annotations.Nullable /** * A `Behavior` for a persistent actor with durable storage of its state. diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/PersistencePlugin.scala b/persistence/src/main/scala/org/apache/pekko/persistence/PersistencePlugin.scala index 85e23d44e1d..2ac73b6acdd 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/PersistencePlugin.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/PersistencePlugin.scala @@ -51,8 +51,8 @@ private[pekko] trait PluginProvider[T, ScalaDsl, JavaDsl] { * INTERNAL API */ @InternalApi -private[pekko] abstract class PersistencePlugin[ScalaDsl, JavaDsl, T: ClassTag](system: ExtendedActorSystem)( - implicit ev: PluginProvider[T, ScalaDsl, JavaDsl]) { +private[pekko] abstract class PersistencePlugin[ScalaDsl, JavaDsl, T](system: ExtendedActorSystem)( + implicit ct: ClassTag[T], ev: PluginProvider[T, ScalaDsl, JavaDsl]) { private val plugins = new AtomicReference[Map[String, ExtensionId[PluginHolder[ScalaDsl, JavaDsl]]]](Map.empty) private val log = Logging(system, classOf[PersistencePlugin[?, ?, ?]]) diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbCompaction.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbCompaction.scala index b21f9205440..46cd1789ff5 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbCompaction.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbCompaction.scala @@ -71,7 +71,7 @@ private[persistence] trait CompactionSegmentManagement { import CompactionSegmentManagement._ - private[this] var latestCompactionSegments = Map.empty[String, Long] + private var latestCompactionSegments = Map.empty[String, Long] def compactionIntervals: Map[String, Long] diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/journal/AsyncWriteJournalResponseOrderSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/journal/AsyncWriteJournalResponseOrderSpec.scala index 3f3537c0eec..1b8097e003f 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/journal/AsyncWriteJournalResponseOrderSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/journal/AsyncWriteJournalResponseOrderSpec.scala @@ -17,12 +17,12 @@ package org.apache.pekko.persistence.journal -import org.apache.pekko.persistence.journal.AsyncWriteJournalResponseOrderSpec._ - import scala.collection.{ immutable, mutable } import scala.concurrent.{ ExecutionContext, Future, Promise } import scala.util.Try + import org.apache.pekko.persistence.{ AtomicWrite, JournalProtocol, PersistenceSpec, PersistentRepr } +import org.apache.pekko.persistence.journal.AsyncWriteJournalResponseOrderSpec._ import org.apache.pekko.testkit.ImplicitSender /** diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/journal/SteppingInmemJournal.scala b/persistence/src/test/scala/org/apache/pekko/persistence/journal/SteppingInmemJournal.scala index 9ff0473f8e5..0a228b5807c 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/journal/SteppingInmemJournal.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/journal/SteppingInmemJournal.scala @@ -51,7 +51,7 @@ object SteppingInmemJournal { // keep it in a thread safe:d global so that tests can get their // hand on the actor ref and send Steps to it - private[this] var _current: Map[String, ActorRef] = Map() + private var _current: Map[String, ActorRef] = Map() // shhh don't tell anyone I sinn-croniz-ed /** get the actor ref to the journal for a given instance id, throws exception if not found */ diff --git a/project/Jdk9.scala b/project/Jdk9.scala index 12275d13bc6..70821d88a67 100644 --- a/project/Jdk9.scala +++ b/project/Jdk9.scala @@ -53,16 +53,27 @@ object Jdk9 extends AutoPlugin { yield (task / sourceDirectory).value / sourceDirectoryName } + private def releaseOption(scalaVer: String): Seq[String] = { + val isScala3_8Plus = scalaVer.startsWith("3.") && { + val parts = scalaVer.split('.') + def safeToInt(s: String): Int = try { s.split('-').head.toInt } + catch { case _: NumberFormatException => 0 } + parts.length >= 2 && (safeToInt(parts(1)) >= 8 || safeToInt(parts(0)) > 3) + } + if (isScala3_8Plus) Seq("-java-output-version", majorVersion.toString) + else Seq("-release", majorVersion.toString) + } + lazy val compileJdk9Settings = Seq( // following the scala-2.12, scala-sbt-1.0, ... convention unmanagedSourceDirectories := additionalSourceDirectories.value, - scalacOptions := PekkoBuild.DefaultScalacOptions.value ++ Seq("-release", majorVersion.toString), + scalacOptions := PekkoBuild.DefaultScalacOptions.value ++ releaseOption(scalaVersion.value), javacOptions := PekkoBuild.DefaultJavacOptions ++ Seq("--release", majorVersion.toString)) lazy val testJdk9Settings = Seq( // following the scala-2.12, scala-sbt-1.0, ... convention unmanagedSourceDirectories := additionalTestSourceDirectories.value, - scalacOptions := PekkoBuild.DefaultScalacOptions.value ++ Seq("-release", majorVersion.toString), + scalacOptions := PekkoBuild.DefaultScalacOptions.value ++ releaseOption(scalaVersion.value), javacOptions := PekkoBuild.DefaultJavacOptions ++ Seq("--release", majorVersion.toString), compile := compile.dependsOn(CompileJdk9 / compile).value, classpathConfiguration := TestJdk9, diff --git a/project/JdkOptions.scala b/project/JdkOptions.scala index 99291c99e10..ee30683d2a8 100644 --- a/project/JdkOptions.scala +++ b/project/JdkOptions.scala @@ -35,10 +35,21 @@ object JdkOptions extends AutoPlugin { // for LevelDB "--add-opens=java.base/java.nio=ALL-UNNAMED" :: Nil - def targetJdkScalacOptions(scalaVersion: String): Seq[String] = - Seq("-release", JdkOptions.targetJavaVersion) ++ { - if (scalaVersion.startsWith("3.")) Seq(s"-Xtarget:${targetJavaVersion}") else Seq.empty + def targetJdkScalacOptions(scalaVersion: String): Seq[String] = { + val isScala3_8Plus = scalaVersion.startsWith("3.") && { + val parts = scalaVersion.split('.') + def safeToInt(s: String): Int = try { s.split('-').head.toInt } + catch { case _: NumberFormatException => 0 } + parts.length >= 2 && (safeToInt(parts(1)) >= 8 || safeToInt(parts(0)) > 3) } + if (isScala3_8Plus) { + Seq("-java-output-version", JdkOptions.targetJavaVersion) + } else { + Seq("-release", JdkOptions.targetJavaVersion) ++ { + if (scalaVersion.startsWith("3.")) Seq(s"-Xtarget:${targetJavaVersion}") else Seq.empty + } + } + } val targetJdkJavacOptions = Seq("--release", targetJavaVersion) } diff --git a/project/PekkoDisciplinePlugin.scala b/project/PekkoDisciplinePlugin.scala index 48212954c20..22da8a972e7 100644 --- a/project/PekkoDisciplinePlugin.scala +++ b/project/PekkoDisciplinePlugin.scala @@ -75,20 +75,30 @@ object PekkoDisciplinePlugin extends AutoPlugin { "pekko-testkit") lazy val defaultScalaOptions = Def.setting(CrossVersion.partialVersion(scalaVersion.value).get match { - case (3, _) => "-Wconf:cat=unused-nowarn:s,cat=other-shadowing:s,any:e" - case (2, 13) => "-Wconf:any:e,cat=unused-nowarn:s,cat=other-shadowing:s" - case (2, 12) => "-Wconf:cat=unused-nowarn:s,any:e" + case (3, _) => + Seq( + "-Wconf:cat=unused-nowarn:s,cat=other-shadowing:s," + + "msg=Implicit parameters should be provided with a .using. clause:s," + + "msg=is no longer supported for vararg splices:s," + + "msg=with as a type operator has been deprecated:s," + + "msg=SerialVersionUID does nothing on a trait:s," + + "msg=has been deprecated.*use .= uninitialized. instead:s," + + "msg=trailing.*_.*for eta-expansion is unnecessary:s," + + "msg=is not declared infix:s," + + "msg=._. is deprecated for wildcard arguments of types:s," + + "msg=Ignoring ..this.. qualifier:s," + + "msg=Unreachable case except for null:s," + + "msg=Classic remoting is deprecated:s," + + "msg=Use EventSourcedBehavior:s," + + "msg=migration-to-pekko-grpc:s," + + "any:e") + case (2, 13) => Seq("-Wconf:any:e,cat=unused-nowarn:s,cat=other-shadowing:s") + case (2, 12) => Seq("-Wconf:cat=unused-nowarn:s,any:e") }) lazy val nowarnSettings = Seq( - Compile / scalacOptions ++= ( - if (scalaVersion.value.startsWith("3.")) Nil - else Seq(defaultScalaOptions.value) - ), - Test / scalacOptions ++= ( - if (scalaVersion.value.startsWith("3.")) Nil - else Seq(defaultScalaOptions.value) - ), + Compile / scalacOptions ++= defaultScalaOptions.value, + Test / scalacOptions ++= defaultScalaOptions.value, Compile / doc / scalacOptions := Seq()) // ignore Scala compile warnings for Java 20+ @@ -101,20 +111,48 @@ object PekkoDisciplinePlugin extends AutoPlugin { */ lazy val docs = Seq( - Compile / scalacOptions -= defaultScalaOptions.value, + Compile / scalacOptions --= defaultScalaOptions.value, Compile / scalacOptions ++= (CrossVersion.partialVersion(scalaVersion.value).get match { - case (3, _) => Nil - case (2, 13) => Seq("-Wconf:any:e,cat=unused:s,cat=deprecation:s,cat=unchecked:s") - case (2, 12) => Seq("-Wconf:cat=unused:s,cat=deprecation:s,cat=unchecked:s,any:e") + case (3, _) => + Seq( + "-Wconf:cat=unused:s,cat=deprecation:s,cat=unchecked:s," + + "msg=Implicit parameters should be provided with a .using. clause:s," + + "msg=is no longer supported for vararg splices:s," + + "msg=with as a type operator has been deprecated:s," + + "msg=SerialVersionUID does nothing on a trait:s," + + "msg=has been deprecated.*use .= uninitialized. instead:s," + + "msg=trailing.*_.*for eta-expansion is unnecessary:s," + + "msg=is not declared infix:s," + + "msg=._. is deprecated for wildcard arguments of types:s," + + "msg=Ignoring ..this.. qualifier:s," + + "any:e") + case (2, 13) => + Seq("-Wconf:any:e,cat=unused:s,cat=deprecation:s,cat=unchecked:s") + case (2, 12) => + Seq("-Wconf:cat=unused:s,cat=deprecation:s,cat=unchecked:s,any:e") }), Test / scalacOptions --= Seq("-Xlint", "-unchecked", "-deprecation"), - Test / scalacOptions -= defaultScalaOptions.value, + Test / scalacOptions --= defaultScalaOptions.value, Test / scalacOptions ++= (CrossVersion.partialVersion(scalaVersion.value).get match { - case (3, _) => Nil - case (2, 13) => Seq("-Wconf:any:e,cat=unused:s,cat=deprecation:s,cat=unchecked:s") - case (2, 12) => Seq("-Wconf:cat=unused:s,cat=deprecation:s,cat=unchecked:s,any:e") + case (3, _) => + Seq( + "-Wconf:cat=unused:s,cat=deprecation:s,cat=unchecked:s," + + "msg=Implicit parameters should be provided with a .using. clause:s," + + "msg=is no longer supported for vararg splices:s," + + "msg=with as a type operator has been deprecated:s," + + "msg=SerialVersionUID does nothing on a trait:s," + + "msg=has been deprecated.*use .= uninitialized. instead:s," + + "msg=trailing.*_.*for eta-expansion is unnecessary:s," + + "msg=is not declared infix:s," + + "msg=._. is deprecated for wildcard arguments of types:s," + + "msg=Ignoring ..this.. qualifier:s," + + "any:e") + case (2, 13) => + Seq("-Wconf:any:e,cat=unused:s,cat=deprecation:s,cat=unchecked:s") + case (2, 12) => + Seq("-Wconf:cat=unused:s,cat=deprecation:s,cat=unchecked:s,any:e") }), Compile / doc / scalacOptions := Seq()) diff --git a/project/SbtMultiJvmPlugin.scala b/project/SbtMultiJvmPlugin.scala index 01c484f9865..c49f915c0dc 100644 --- a/project/SbtMultiJvmPlugin.scala +++ b/project/SbtMultiJvmPlugin.scala @@ -84,14 +84,14 @@ object MultiJvmPlugin extends AutoPlugin { override lazy val projectSettings = multiJvmSettings - private[this] def noTestsMessage(scoped: ScopedKey[?])(implicit display: Show[ScopedKey[?]]): String = + private def noTestsMessage(scoped: ScopedKey[?])(implicit display: Show[ScopedKey[?]]): String = "No tests to run for " + display.show(scoped) lazy val multiJvmSettings: Seq[Def.Setting[?]] = inConfig(MultiJvm)(Defaults.configSettings ++ internalMultiJvmSettings) // https://github.com/sbt/sbt/blob/v0.13.15/main/actions/src/main/scala/sbt/Tests.scala#L296-L298 - private[this] def showResults(log: Logger, results: Tests.Output, noTestsMessage: => String): Unit = + private def showResults(log: Logger, results: Tests.Output, noTestsMessage: => String): Unit = TestResultLogger.Default.copy(printNoTests = TestResultLogger.const(_.info(noTestsMessage))).run(log, results, "") private def internalMultiJvmSettings = diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala index 9e78a90f3cb..6c32947673d 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala @@ -59,8 +59,8 @@ object AeronStreamMaxThroughputSpec extends MultiNodeConfig { final case class TestSettings(testName: String, totalMessages: Long, payloadSize: Int) def iterate(start: Long, end: Long): Iterator[Long] = new AbstractIterator[Long] { - private[this] var first = true - private[this] var acc = start + private var first = true + private var acc = start def hasNext: Boolean = acc < end def next(): Long = { if (!hasNext) throw new NoSuchElementException("next on empty iterator") diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/ArteryTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/ArteryTransport.scala index b9bcfd45ef7..ba3f8e650b3 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/ArteryTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/ArteryTransport.scala @@ -285,13 +285,13 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr type LifeCycle // these vars are initialized once in the start method - @volatile private[this] var _localAddress: UniqueAddress = _ - @volatile private[this] var _bindAddress: UniqueAddress = _ - @volatile private[this] var _addresses: Set[Address] = _ + @volatile private var _localAddress: UniqueAddress = _ + @volatile private var _bindAddress: UniqueAddress = _ + @volatile private var _addresses: Set[Address] = _ @volatile protected var materializer: Materializer = _ @volatile protected var controlMaterializer: Materializer = _ - @volatile private[this] var controlSubject: ControlMessageSubject = _ - @volatile private[this] var messageDispatcher: MessageDispatcher = _ + @volatile private var controlSubject: ControlMessageSubject = _ + @volatile private var messageDispatcher: MessageDispatcher = _ override val log: MarkerLoggingAdapter = Logging.withMarker(system, classOf[ArteryTransport]) @@ -310,7 +310,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr } else NoInboundCompressions } - @volatile private[this] var _inboundCompressionAccess: OptionVal[InboundCompressionAccess] = OptionVal.None + @volatile private var _inboundCompressionAccess: OptionVal[InboundCompressionAccess] = OptionVal.None /** Only access compression tables via the CompressionAccess */ def inboundCompressionAccess: OptionVal[InboundCompressionAccess] = _inboundCompressionAccess @@ -327,7 +327,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr // keyed by the streamId protected val streamMatValues = new AtomicReference(Map.empty[Int, InboundStreamMatValues[LifeCycle]]) - private[this] val hasBeenShutdown = new AtomicBoolean(false) + private val hasBeenShutdown = new AtomicBoolean(false) private val testState = new SharedTestState diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/Association.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/Association.scala index d2e543414d2..eb9bf1176a5 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/Association.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/Association.scala @@ -181,7 +181,7 @@ private[remote] class Association( private val queueSize = advancedSettings.OutboundMessageQueueSize private val largeQueueSize = advancedSettings.OutboundLargeMessageQueueSize - private[this] val queues: Array[SendQueue.ProducerApi[OutboundEnvelope]] = new Array(2 + outboundLanes) + private val queues: Array[SendQueue.ProducerApi[OutboundEnvelope]] = new Array(2 + outboundLanes) queues(ControlQueueIndex) = QueueWrapperImpl(createQueue(controlQueueSize, ControlQueueIndex)) // control stream queues(LargeQueueIndex) = if (transport.largeMessageChannelEnabled) // large messages stream @@ -192,19 +192,19 @@ private[remote] class Association( (0 until outboundLanes).foreach { i => queues(OrdinaryQueueIndex + i) = QueueWrapperImpl(createQueue(queueSize, OrdinaryQueueIndex + i)) // ordinary messages stream } - @volatile private[this] var queuesVisibility = false + @volatile private var queuesVisibility = false private def controlQueue: SendQueue.ProducerApi[OutboundEnvelope] = queues(ControlQueueIndex) - @volatile private[this] var _outboundControlIngress: OptionVal[OutboundControlIngress] = OptionVal.None - @volatile private[this] var materializing = new CountDownLatch(1) - @volatile private[this] var outboundCompressionAccess: Vector[OutboundCompressionAccess] = Vector.empty + @volatile private var _outboundControlIngress: OptionVal[OutboundControlIngress] = OptionVal.None + @volatile private var materializing = new CountDownLatch(1) + @volatile private var outboundCompressionAccess: Vector[OutboundCompressionAccess] = Vector.empty // keyed by stream queue index - private[this] val streamMatValues = new AtomicReference(Map.empty[Int, OutboundStreamMatValues]) + private val streamMatValues = new AtomicReference(Map.empty[Int, OutboundStreamMatValues]) - private[this] val idleTimer = new AtomicReference[Option[Cancellable]](None) - private[this] val stopQuarantinedTimer = new AtomicReference[Option[Cancellable]](None) + private val idleTimer = new AtomicReference[Option[Cancellable]](None) + private val stopQuarantinedTimer = new AtomicReference[Option[Cancellable]](None) private[remote] def changeActorRefCompression(table: CompressionTable[ActorRef]): Future[Done] = updateOutboundCompression(c => c.changeActorRefCompression(table)) @@ -1132,8 +1132,8 @@ private[remote] class Association( * INTERNAL API */ private[remote] class AssociationRegistry(createAssociation: Address => Association) { - private[this] val associationsByAddress = new AtomicReference[Map[Address, Association]](Map.empty) - private[this] val associationsByUid = new AtomicReference[ImmutableLongMap[Association]](ImmutableLongMap.empty) + private val associationsByAddress = new AtomicReference[Map[Address, Association]](Map.empty) + private val associationsByUid = new AtomicReference[ImmutableLongMap[Association]](ImmutableLongMap.empty) /** * @throws ShuttingDown if called while the transport is shutting down diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/EnvelopeBufferPool.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/EnvelopeBufferPool.scala index 5da684ebe03..267c33cd24c 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/EnvelopeBufferPool.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/EnvelopeBufferPool.scala @@ -240,7 +240,7 @@ private[remote] final class HeaderBuilderImpl( extends HeaderBuilder { import HeaderBuilder.DeadLettersCode - private[this] val toSerializationFormat: SerializationFormatCache = new SerializationFormatCache + private val toSerializationFormat: SerializationFormatCache = new SerializationFormatCache // Fields only available for EnvelopeBuffer var _version: Byte = 0 diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/LruBoundedCache.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/LruBoundedCache.scala index 669ae73b35a..e145a7e1c93 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/LruBoundedCache.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/LruBoundedCache.scala @@ -39,15 +39,15 @@ private[pekko] abstract class LruBoundedCache[K <: AnyRef: ClassTag, V <: AnyRef require((capacity & (capacity - 1)) == 0, "Capacity must be power of two") require(evictAgeThreshold <= capacity, "Age threshold must be less than capacity.") - private[this] val Mask = capacity - 1 + private val Mask = capacity - 1 // Practically guarantee an overflow - private[this] var epoch = Int.MaxValue - 1 + private var epoch = Int.MaxValue - 1 - private[this] val keys = Array.ofDim[K](capacity) - private[this] val values = Array.ofDim[V](capacity) - private[this] val hashes = new Array[Int](capacity) - private[this] val epochs = Array.fill[Int](capacity)(epoch - evictAgeThreshold) // Guarantee existing "values" are stale + private val keys = Array.ofDim[K](capacity) + private val values = Array.ofDim[V](capacity) + private val hashes = new Array[Int](capacity) + private val epochs = Array.fill[Int](capacity)(epoch - evictAgeThreshold) // Guarantee existing "values" are stale final def get(k: K): Option[V] = { val h = hash(k) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/ArteryAeronUdpTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/ArteryAeronUdpTransport.scala index be3f89c477c..93160b85ba2 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/ArteryAeronUdpTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/ArteryAeronUdpTransport.scala @@ -69,11 +69,11 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro override type LifeCycle = AeronLifecycle - private[this] val mediaDriver = new AtomicReference[Option[MediaDriver]](None) - @volatile private[this] var aeron: Aeron = _ - @volatile private[this] var aeronCounterTask: Cancellable = _ - @volatile private[this] var aeronErrorLogTask: Cancellable = _ - @volatile private[this] var aeronErrorLog: AeronErrorLog = _ + private val mediaDriver = new AtomicReference[Option[MediaDriver]](None) + @volatile private var aeron: Aeron = _ + @volatile private var aeronCounterTask: Cancellable = _ + @volatile private var aeronErrorLogTask: Cancellable = _ + @volatile private var aeronErrorLog: AeronErrorLog = _ private val taskRunner = new TaskRunner(system, settings.Advanced.Aeron.IdleCpuLevel) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/TaskRunner.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/TaskRunner.scala index a757de28586..706b72b51c8 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/TaskRunner.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/TaskRunner.scala @@ -127,10 +127,10 @@ private[pekko] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: I import TaskRunner._ private val log = Logging(system, classOf[TaskRunner]) - private[this] var running = false - private[this] val cmdQueue = new CommandQueue - private[this] val tasks = new ArrayBag[Task] - private[this] val shutdown = Promise[Done]() + private var running = false + private val cmdQueue = new CommandQueue + private val tasks = new ArrayBag[Task] + private val shutdown = Promise[Done]() private val idleStrategy = createIdleStrategy(idleCpuLevel) private var reset = false diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/DecompressionTable.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/DecompressionTable.scala index 1279eddf0b9..575725ff258 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/DecompressionTable.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/DecompressionTable.scala @@ -20,7 +20,7 @@ package org.apache.pekko.remote.artery.compress */ private[remote] final case class DecompressionTable[T](originUid: Long, version: Byte, table: Array[T]) { - private[this] val length = table.length + private val length = table.length def get(idx: Int): T = { if (idx >= length) @@ -44,7 +44,7 @@ private[remote] object DecompressionTable { val DisabledVersion: Byte = -1 - private[this] val _empty = DecompressionTable(0, 0, Array.empty[Any]) + private val _empty = DecompressionTable(0, 0, Array.empty[Any]) def empty[T] = _empty.asInstanceOf[DecompressionTable[T]] def disabled[T] = empty[T].copy(version = DisabledVersion) } diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/InboundCompressions.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/InboundCompressions.scala index 4238af24906..dbb43678a84 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/InboundCompressions.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/InboundCompressions.scala @@ -73,8 +73,8 @@ private[remote] final class InboundCompressionsImpl( flightRecorder: RemotingFlightRecorder = NoOpRemotingFlightRecorder) extends InboundCompressions { - private[this] val _actorRefsIns = new Long2ObjectHashMap[InboundActorRefCompression]() - private[this] val _inboundActorRefsLog = Logging(system, classOf[InboundActorRefCompression]) + private val _actorRefsIns = new Long2ObjectHashMap[InboundActorRefCompression]() + private val _inboundActorRefsLog = Logging(system, classOf[InboundActorRefCompression]) private val createInboundActorRefsForOrigin = new LongFunction[InboundActorRefCompression] { override def apply(originUid: Long): InboundActorRefCompression = { val actorRefHitters = new TopHeavyHitters[ActorRef](settings.ActorRefs.Max) @@ -84,9 +84,9 @@ private[remote] final class InboundCompressionsImpl( private def actorRefsIn(originUid: Long): InboundActorRefCompression = _actorRefsIns.computeIfAbsent(originUid, createInboundActorRefsForOrigin) - private[this] val _classManifestsIns = new Long2ObjectHashMap[InboundManifestCompression]() + private val _classManifestsIns = new Long2ObjectHashMap[InboundManifestCompression]() - private[this] val _inboundManifestLog = Logging(system, classOf[InboundManifestCompression]) + private val _inboundManifestLog = Logging(system, classOf[InboundManifestCompression]) private val createInboundManifestsForOrigin = new LongFunction[InboundManifestCompression] { override def apply(originUid: Long): InboundManifestCompression = { val manifestHitters = new TopHeavyHitters[String](settings.Manifests.Max) @@ -345,14 +345,14 @@ private[remote] abstract class InboundCompression[T >: Null]( inboundContext: InboundContext, val heavyHitters: TopHeavyHitters[T]) { - private[this] var tables: InboundCompression.Tables[T] = InboundCompression.Tables.empty + private var tables: InboundCompression.Tables[T] = InboundCompression.Tables.empty // We should not continue sending advertisements to an association that might be dead (not quarantined yet) - @volatile private[this] var alive = true - private[this] var resendCount = 0 - private[this] val maxResendCount = 3 + @volatile private var alive = true + private var resendCount = 0 + private val maxResendCount = 3 - private[this] val cms = new CountMinSketch(16, 1024, System.currentTimeMillis().toInt) + private val cms = new CountMinSketch(16, 1024, System.currentTimeMillis().toInt) log.debug("Initializing {} for originUid [{}]", Logging.simpleName(getClass), originUid) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/TopHeavyHitters.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/TopHeavyHitters.scala index be6e27f5327..c5458c9ed63 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/TopHeavyHitters.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/TopHeavyHitters.scala @@ -46,17 +46,17 @@ private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit cl // Contains the hash value for each entry in the hashmap. Used for quicker lookups (equality check can be avoided // if hashes don't match) - private[this] val hashes: Array[Int] = new Array(capacity) + private val hashes: Array[Int] = new Array(capacity) // Actual stored elements in the hashmap - private[this] val items: Array[T] = Array.ofDim[T](capacity) + private val items: Array[T] = Array.ofDim[T](capacity) // Index of stored element in the associated heap - private[this] val heapIndex: Array[Int] = Array.fill(capacity)(-1) + private val heapIndex: Array[Int] = Array.fill(capacity)(-1) // Weights associated with an entry in the hashmap. Used to maintain the heap property and give easy access to low // weight entries - private[this] val weights: Array[Long] = new Array(capacity) + private val weights: Array[Long] = new Array(capacity) // Heap structure containing indices to slots in the hashmap - private[this] val heap: Array[Int] = Array.fill(adjustedMax)(-1) + private val heap: Array[Int] = Array.fill(adjustedMax)(-1) /* * Invariants (apart from heap and hashmap invariants): diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyTransport.scala index 6cad95e682c..f64a39ac02c 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyTransport.scala @@ -140,7 +140,7 @@ class NettyTransportSettings(config: Config) { case dispatcher => Some(dispatcher) } - private[this] def optionSize(s: String): Option[Int] = getBytes(s).toInt match { + private def optionSize(s: String): Option[Int] = getBytes(s).toInt match { case 0 => None case x if x < 0 => throw new ConfigurationException(s"Setting '$s' must be 0 or positive (and fit in an Int)") case other => Some(other) diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/MetadataCarryingSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/MetadataCarryingSpec.scala index a1f50c4e929..32aa6c9bb06 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/MetadataCarryingSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/MetadataCarryingSpec.scala @@ -40,7 +40,7 @@ object MetadataCarryingSpy extends ExtensionId[MetadataCarryingSpy] with Extensi class MetadataCarryingSpy extends Extension { def ref: Option[ActorRef] = Option(_ref.get()) def setProbe(bs: ActorRef): Unit = _ref.set(bs) - private[this] val _ref = new AtomicReference[ActorRef]() + private val _ref = new AtomicReference[ActorRef]() } class TestInstrument(system: ExtendedActorSystem) extends RemoteInstrument { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProviderSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProviderSpec.scala index 2cda6257f63..670e0a33919 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProviderSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProviderSpec.scala @@ -45,9 +45,10 @@ import pekko.testkit.TestActors import pekko.testkit.TestProbe import pekko.util.JavaVersion -import com.typesafe.config.ConfigFactory import org.scalatest.Outcome +import com.typesafe.config.ConfigFactory + // This is a simplification Spec. It doesn't rely on changing files. class RotatingProviderWithStaticKeysSpec extends RotatingKeysSSLEngineProviderSpec(RotatingKeysSSLEngineProviderSpec.resourcesConfig) { diff --git a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/StreamTestKit.scala b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/StreamTestKit.scala index 01193b39dc1..909be24d304 100644 --- a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/StreamTestKit.scala +++ b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/StreamTestKit.scala @@ -370,8 +370,10 @@ object TestPublisher { /** * Java API */ - def expectCancellationWithCause[E <: Throwable](causeClass: Class[E]): E = - expectCancellationWithCause()(ClassTag(causeClass)) + def expectCancellationWithCause[E <: Throwable](causeClass: Class[E]): E = { + implicit val ct: ClassTag[E] = ClassTag(causeClass) + expectCancellationWithCause() + } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/FanoutPublisherBehaviorSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/FanoutPublisherBehaviorSpec.scala index 884db05a05d..94357b9cf0a 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/FanoutPublisherBehaviorSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/FanoutPublisherBehaviorSpec.scala @@ -21,7 +21,6 @@ import scala.concurrent.Await import scala.concurrent.duration._ import org.apache.pekko -import pekko.testkit.EventFilter import pekko.stream.{ AbruptStageTerminationException, ActorAttributes, @@ -32,11 +31,12 @@ import pekko.stream.{ import pekko.stream.scaladsl.Keep import pekko.stream.scaladsl.Sink import pekko.stream.scaladsl.Source -import pekko.stream.testkit.TestPublisher import pekko.stream.testkit.StreamSpec +import pekko.stream.testkit.TestPublisher import pekko.stream.testkit.TestSubscriber -import pekko.stream.testkit.scaladsl.TestSink import pekko.stream.testkit.Utils.TE +import pekko.stream.testkit.scaladsl.TestSink +import pekko.testkit.EventFilter class FanoutPublisherBehaviorSpec extends StreamSpec { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/FixedBufferSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/FixedBufferSpec.scala index 25f5437fdbe..a3d27efaf65 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/FixedBufferSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/FixedBufferSpec.scala @@ -113,8 +113,8 @@ class FixedBufferSpec extends StreamSpec { try { val cheat = buf.asInstanceOf[{ def readIdx_=(l: Long): Unit; def writeIdx_=(l: Long): Unit }] - cheat.readIdx_=(Int.MaxValue) - cheat.writeIdx_=(Int.MaxValue) + val _: Unit = cheat.readIdx_=(Int.MaxValue) + val _: Unit = cheat.writeIdx_=(Int.MaxValue) for (_ <- 1 to 10) { buf.isEmpty should be(true) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/TraversalBuilderSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/TraversalBuilderSpec.scala index 3557352d945..9bff87c4aca 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/TraversalBuilderSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/TraversalBuilderSpec.scala @@ -18,10 +18,10 @@ import scala.concurrent.Promise import org.apache.pekko import pekko.NotUsed import pekko.stream._ -import pekko.stream.impl.TraversalTestUtils._ import pekko.stream.impl.Stages.DefaultAttributes -import pekko.stream.impl.fusing.GraphStages.{ FutureSource, RepeatSource, SingleSource } +import pekko.stream.impl.TraversalTestUtils._ import pekko.stream.impl.fusing.{ IterableSource, IteratorSource, RangeSource } +import pekko.stream.impl.fusing.GraphStages.{ FutureSource, RepeatSource, SingleSource } import pekko.stream.scaladsl.{ Keep, Source } import pekko.testkit.PekkoSpec import pekko.util.OptionVal diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSinkSpec.scala index 30e208af68d..e3cfc925246 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSinkSpec.scala @@ -26,13 +26,13 @@ import com.google.common.jimfs.{ Configuration, Jimfs } import org.apache.pekko import pekko.stream._ +import pekko.stream.SystemMaterializer import pekko.stream.impl.{ PhasedFusingActorMaterializer, StreamSupervisor } import pekko.stream.impl.StreamSupervisor.Children import pekko.stream.scaladsl.{ FileIO, Keep, Source } import pekko.stream.testkit._ import pekko.stream.testkit.Utils._ import pekko.util.ByteString -import pekko.stream.SystemMaterializer import org.scalatest.concurrent.ScalaFutures diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala index 8f6a417568c..e5d94c37ca2 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala @@ -26,6 +26,7 @@ import com.google.common.jimfs.{ Configuration, Jimfs } import org.apache.pekko import pekko.stream._ import pekko.stream.IOResult._ +import pekko.stream.SystemMaterializer import pekko.stream.impl.{ PhasedFusingActorMaterializer, StreamSupervisor } import pekko.stream.impl.StreamSupervisor.Children import pekko.stream.io.FileSourceSpec.Settings @@ -34,7 +35,6 @@ import pekko.stream.testkit._ import pekko.stream.testkit.Utils._ import pekko.stream.testkit.scaladsl.TestSink import pekko.util.ByteString -import pekko.stream.SystemMaterializer object FileSourceSpec { final case class Settings(chunkSize: Int, readAhead: Int) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/TlsGraphStageEdgeCasesSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/TlsGraphStageEdgeCasesSpec.scala index 718867a9b83..5f6f471179d 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/TlsGraphStageEdgeCasesSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/TlsGraphStageEdgeCasesSpec.scala @@ -17,16 +17,13 @@ package org.apache.pekko.stream.io -import javax.net.ssl.{ SSLContext, SSLEngine, SSLSession } - import java.util.concurrent.atomic.AtomicInteger +import javax.net.ssl.{ SSLContext, SSLEngine, SSLSession } import scala.concurrent.Await import scala.concurrent.duration._ import scala.util.{ Success, Try } -import com.typesafe.config.ConfigFactory - import org.apache.pekko import pekko.NotUsed import pekko.stream._ @@ -37,6 +34,8 @@ import pekko.stream.testkit.StreamSpec import pekko.testkit.TestDuration import pekko.util.ByteString +import com.typesafe.config.ConfigFactory + /** * Edge cases for the [[TlsGraphStage]] path that are awkward to express in the * shared [[TlsGraphStageSpec]] matrix: fragmented TLS records, user-side diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/DeflateAutoFlushSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/DeflateAutoFlushSpec.scala index 284aaa3ae19..e7f2c0c8c07 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/DeflateAutoFlushSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/DeflateAutoFlushSpec.scala @@ -17,11 +17,11 @@ package org.apache.pekko.stream.io.compression +import java.util.zip.Deflater + import org.apache.pekko.stream.scaladsl.{ Compression, Flow } import org.apache.pekko.util.ByteString -import java.util.zip.Deflater - class DeflateAutoFlushSpec extends DeflateSpec { override protected val encoderFlow: Flow[ByteString, ByteString, Any] = Compression.deflate(Deflater.BEST_COMPRESSION, nowrap = false, autoFlush = false) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/GzipAutoFlushSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/GzipAutoFlushSpec.scala index 031c19428b2..d0e83e1fc5f 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/GzipAutoFlushSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/GzipAutoFlushSpec.scala @@ -17,11 +17,11 @@ package org.apache.pekko.stream.io.compression +import java.util.zip.Deflater + import org.apache.pekko.stream.scaladsl.{ Compression, Flow } import org.apache.pekko.util.ByteString -import java.util.zip.Deflater - class GzipAutoFlushSpec extends GzipSpec { override protected val encoderFlow: Flow[ByteString, ByteString, Any] = Compression.gzip(Deflater.BEST_COMPRESSION, autoFlush = false) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkSpec.scala index 87ea68ce865..11689a3ac70 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkSpec.scala @@ -14,6 +14,7 @@ package org.apache.pekko.stream.scaladsl import scala.annotation.nowarn +import scala.collection.immutable import scala.concurrent.{ Await, Future } import scala.concurrent.duration._ @@ -25,8 +26,6 @@ import pekko.stream.testkit._ import pekko.stream.testkit.scaladsl.{ TestSink, TestSource } import pekko.testkit.DefaultTimeout -import scala.collection.immutable - import org.reactivestreams.Publisher import org.scalatest.concurrent.ScalaFutures diff --git a/stream/src/main/boilerplate/org/apache/pekko/stream/scaladsl/ZipLatestWithApply.scala.template b/stream/src/main/boilerplate/org/apache/pekko/stream/scaladsl/ZipLatestWithApply.scala.template index 80cc5d9baad..d513e5ea638 100644 --- a/stream/src/main/boilerplate/org/apache/pekko/stream/scaladsl/ZipLatestWithApply.scala.template +++ b/stream/src/main/boilerplate/org/apache/pekko/stream/scaladsl/ZipLatestWithApply.scala.template @@ -107,7 +107,7 @@ class ZipLatestWith1[[#A1#], O] (val zipper: ([#A1#]) => O, val eagerComplete: B } private class ZipLatestInlet[T](in: Inlet[T]) extends InHandler { - var value: T = _ + var value: T = null.asInstanceOf[T] var hasValue = false override def onPush() = { diff --git a/stream/src/main/scala/org/apache/pekko/stream/KillSwitch.scala b/stream/src/main/scala/org/apache/pekko/stream/KillSwitch.scala index cd120bf0e12..018538fa01f 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/KillSwitch.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/KillSwitch.scala @@ -171,8 +171,8 @@ private[stream] final class TerminationSignal { def unregister(): Unit = removeListener(this) } - private[this] val _listeners = TrieMap.empty[Listener, NotUsed] - private[this] val _completedWith: AtomicReference[Option[Try[Done]]] = new AtomicReference(None) + private val _listeners = TrieMap.empty[Listener, NotUsed] + private val _completedWith: AtomicReference[Option[Try[Done]]] = new AtomicReference(None) def tryComplete(result: Try[Done]): Unit = { if (_completedWith.compareAndSet(None, Some(result))) { @@ -255,8 +255,8 @@ final class UniqueKillSwitch private[stream] (private val promise: Promise[Done] * This class is thread-safe, the instance can be passed safely among threads and its methods may be invoked concurrently. */ final class SharedKillSwitch private[stream] (val name: String) extends KillSwitch { - private[this] val terminationSignal = new TerminationSignal - private[this] val _flow: Graph[FlowShape[Any, Any], SharedKillSwitch] = new SharedKillSwitchFlow + private val terminationSignal = new TerminationSignal + private val _flow: Graph[FlowShape[Any, Any], SharedKillSwitch] = new SharedKillSwitchFlow /** * After calling [[SharedKillSwitch#shutdown]] all materialized, running instances of all [[Graph]]s provided by the diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/FanIn.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/FanIn.scala index 32cc959efe5..ea16196600c 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/FanIn.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/FanIn.scala @@ -70,7 +70,7 @@ import org.reactivestreams.{ Subscriber, Subscription } } } - private[this] final val states = new Array[State](inputCount) + private final val states = new Array[State](inputCount) private var markCount = 0 private var markedPending = 0 private var markedDepleted = 0 @@ -78,27 +78,27 @@ import org.reactivestreams.{ Subscriber, Subscription } private var receivedInput = false private var completedCounter = 0 - private[this] final def hasState(index: Int, flag: Int): Boolean = (states(index) & flag) != 0 - private[this] final def setState(index: Int, flag: Int, on: Boolean): Unit = + private final def hasState(index: Int, flag: Int): Boolean = (states(index) & flag) != 0 + private final def setState(index: Int, flag: Int, on: Boolean): Unit = states(index) = if (on) (states(index) | flag).toByte else (states(index) & ~flag).toByte - private[this] final def cancelled(index: Int): Boolean = hasState(index, Cancelled) - private[this] final def cancelled(index: Int, on: Boolean): Unit = setState(index, Cancelled, on) + private final def cancelled(index: Int): Boolean = hasState(index, Cancelled) + private final def cancelled(index: Int, on: Boolean): Unit = setState(index, Cancelled, on) - private[this] final def completed(index: Int): Boolean = hasState(index, Completed) - private[this] final def registerCompleted(index: Int): Unit = { + private final def completed(index: Int): Boolean = hasState(index, Completed) + private final def registerCompleted(index: Int): Unit = { completedCounter += 1 setState(index, Completed, true) } - private[this] final def depleted(index: Int): Boolean = hasState(index, Depleted) - private[this] final def depleted(index: Int, on: Boolean): Unit = setState(index, Depleted, on) + private final def depleted(index: Int): Boolean = hasState(index, Depleted) + private final def depleted(index: Int, on: Boolean): Unit = setState(index, Depleted, on) - private[this] final def pending(index: Int): Boolean = hasState(index, Pending) - private[this] final def pending(index: Int, on: Boolean): Unit = setState(index, Pending, on) + private final def pending(index: Int): Boolean = hasState(index, Pending) + private final def pending(index: Int, on: Boolean): Unit = setState(index, Pending, on) - private[this] final def marked(index: Int): Boolean = hasState(index, Marked) - private[this] final def marked(index: Int, on: Boolean): Unit = setState(index, Marked, on) + private final def marked(index: Int): Boolean = hasState(index, Marked) + private final def marked(index: Int, on: Boolean): Unit = setState(index, Marked, on) override def toString: String = s"""|InputBunch diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/FanoutPublisherBridgeStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/FanoutPublisherBridgeStage.scala index e0391d90080..cce6a22e8f8 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/FanoutPublisherBridgeStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/FanoutPublisherBridgeStage.scala @@ -25,10 +25,10 @@ import scala.util.control.NoStackTrace import org.apache.pekko import pekko.annotation.InternalApi +import pekko.stream._ import pekko.stream.ActorAttributes.StreamSubscriptionTimeout import pekko.stream.Attributes.InputBuffer import pekko.stream.StreamSubscriptionTimeoutTerminationMode -import pekko.stream._ import pekko.stream.impl.Stages.DefaultAttributes import pekko.stream.stage.{ AsyncCallback, diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/JsonObjectParser.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/JsonObjectParser.scala index 6f00d61caa9..369835419c1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/JsonObjectParser.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/JsonObjectParser.scala @@ -60,15 +60,15 @@ import pekko.util.ByteString @InternalApi private[pekko] class JsonObjectParser(maximumObjectLength: Int = Int.MaxValue) { import JsonObjectParser._ - private[this] var buffer: Array[Byte] = Array.empty + private var buffer: Array[Byte] = Array.empty - private[this] var pos = 0 // latest position of pointer while scanning for json object end - private[this] var start = 0 // number of chars to drop from the front of the bytestring before emitting (skip whitespace etc) - private[this] var depth = 0 // counter of object-nesting depth, once hits 0 an object should be emitted + private var pos = 0 // latest position of pointer while scanning for json object end + private var start = 0 // number of chars to drop from the front of the bytestring before emitting (skip whitespace etc) + private var depth = 0 // counter of object-nesting depth, once hits 0 an object should be emitted - private[this] var completedObject = false - private[this] var inStringExpression = false - private[this] var inBackslashEscape = false + private var completedObject = false + private var inStringExpression = false + private var inBackslashEscape = false /** * Appends input ByteString to internal buffer. diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/PhasedFusingActorMaterializer.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/PhasedFusingActorMaterializer.scala index 29b6b740c3a..68354706625 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/PhasedFusingActorMaterializer.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/PhasedFusingActorMaterializer.scala @@ -424,7 +424,7 @@ private final case class SavedIslandData( override def withNamePrefix(name: String): PhasedFusingActorMaterializer = this.copy(flowNames = flowNames.copy(name)) - private[this] def createFlowName(): String = flowNames.next() + private def createFlowName(): String = flowNames.next() // note that this will never be overridden on a per-graph-stage basis regardless of more specific attributes override lazy val executionContext: ExecutionContextExecutor = @@ -698,7 +698,7 @@ private[pekko] object GraphStageIsland { islandName: String, subflowFuser: OptionVal[GraphInterpreterShell => ActorRef]) extends PhaseIsland[GraphStageLogic] { - private[this] val logics = new util.ArrayList[GraphStageLogic](16) + private val logics = new util.ArrayList[GraphStageLogic](16) private var connections = new Array[Connection](16) private var maxConnections = 0 @@ -942,7 +942,7 @@ private[pekko] object GraphStageIsland { */ @InternalApi private[pekko] final class ProcessorModulePhase() extends PhaseIsland[Processor[Any, Any]] { override def name: String = "ProcessorModulePhase" - private[this] var processor: Processor[Any, Any] = _ + private var processor: Processor[Any, Any] = _ override def materializeAtomic(mod: AtomicModule[Shape, Any], attributes: Attributes): (Processor[Any, Any], Any) = { val procAndMat = mod.asInstanceOf[ProcessorModule[Any, Any, Any]].createProcessor() diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/ResizableMultiReaderRingBuffer.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/ResizableMultiReaderRingBuffer.scala index fc215f2dab0..1e5c684c78b 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/ResizableMultiReaderRingBuffer.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/ResizableMultiReaderRingBuffer.scala @@ -37,15 +37,15 @@ import org.apache.pekko.annotation.InternalApi Integer.lowestOneBit(initialSize) == initialSize && 0 < initialSize && initialSize <= maxSize, "initialSize must be a power of 2 that is > 0 and <= maxSize") - private[this] val maxSizeBit = Integer.numberOfTrailingZeros(maxSize) - private[this] var array = new Array[Any](initialSize) + private val maxSizeBit = Integer.numberOfTrailingZeros(maxSize) + private var array = new Array[Any](initialSize) /* * two counters counting the number of elements ever written and read; wrap-around is * handled by always looking at differences or masked values */ - private[this] var writeIx = 0 - private[this] var readIx = 0 // the "oldest" of all read cursor indices, i.e. the one that is most behind + private var writeIx = 0 + private var readIx = 0 // the "oldest" of all read cursor indices, i.e. the one that is most behind // current array.length log2, we don't keep it as an extra field because `Integer.numberOfTrailingZeros` // is a JVM intrinsic compiling down to a `BSF` instruction on x86, which is very fast on modern CPUs diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/SinkholeSubscriber.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/SinkholeSubscriber.scala index 4fd02e2162a..2e43555e3c6 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/SinkholeSubscriber.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/SinkholeSubscriber.scala @@ -25,7 +25,7 @@ import org.reactivestreams.{ Subscriber, Subscription } * INTERNAL API */ @InternalApi private[pekko] final class SinkholeSubscriber[T](whenComplete: Promise[Done]) extends Subscriber[T] { - private[this] var running: Boolean = false + private var running: Boolean = false override def onSubscribe(sub: Subscription): Unit = { ReactiveStreamsCompliance.requireNonNullSubscription(sub) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala index de215da3eae..5d61e9f5bfd 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala @@ -170,8 +170,8 @@ import org.reactivestreams.Subscriber override def createLogicAndMaterializedValue(inheritedAttributes: Attributes) = { val p: Promise[immutable.Seq[T]] = Promise() (new GraphStageLogic(shape) with InHandler { - private[this] val buffer = mutable.Queue.empty[T] - private[this] var count = 0 + private val buffer = mutable.Queue.empty[T] + private var count = 0 override def preStart(): Unit = pull(in) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/SubscriberManagement.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/SubscriberManagement.scala index 91c59a6bff6..c44b3c43b79 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/SubscriberManagement.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/SubscriberManagement.scala @@ -93,18 +93,18 @@ private[pekko] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuf */ protected def createSubscription(subscriber: Subscriber[? >: T]): S - private[this] val buffer = new ResizableMultiReaderRingBuffer[T](initialBufferSize, maxBufferSize, this) + private val buffer = new ResizableMultiReaderRingBuffer[T](initialBufferSize, maxBufferSize, this) protected def bufferDebug: String = buffer.toString // optimize for small numbers of subscribers by keeping subscribers in a plain list - private[this] var subscriptions: Subscriptions = Nil + private var subscriptions: Subscriptions = Nil // number of elements already requested but not yet received from upstream - private[this] var pendingFromUpstream: Long = 0 + private var pendingFromUpstream: Long = 0 // if non-null, holds the end-of-stream state - private[this] var endOfStream: EndOfStream = NotReached + private var endOfStream: EndOfStream = NotReached def cursors = subscriptions @@ -158,7 +158,7 @@ private[pekko] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuf } } - private[this] final def requestFromUpstreamIfRequired(): Unit = { + private final def requestFromUpstreamIfRequired(): Unit = { @tailrec def maxRequested(remaining: Subscriptions, result: Long = 0): Long = remaining match { case head :: tail => maxRequested(tail, math.max(head.totalDemand, result)) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/TraversalBuilder.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/TraversalBuilder.scala index 980d56c0210..45a6eeca8f5 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/TraversalBuilder.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/TraversalBuilder.scala @@ -691,8 +691,8 @@ import pekko.util.OptionVal private val cachedEmptyLinear = LinearTraversalBuilder(OptionVal.None, OptionVal.None, 0, 0, PushNotUsed, OptionVal.None, Attributes.none) - private[this] final val wireBackward: Array[Int] = Array(-1) - private[this] final val noWire: Array[Int] = Array() + private final val wireBackward: Array[Int] = Array(-1) + private final val noWire: Array[Int] = Array() def empty(attributes: Attributes = Attributes.none): LinearTraversalBuilder = if (attributes eq Attributes.none) cachedEmptyLinear diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/Unfold.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/Unfold.scala index 44cf73d6d78..9bcd869b5cf 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/Unfold.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/Unfold.scala @@ -36,7 +36,7 @@ import pekko.stream.stage.{ GraphStage, GraphStageLogic, OutHandler } override def initialAttributes: Attributes = DefaultAttributes.unfold and SourceLocation.forLambda(f) override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler { - private[this] var state = s + private var state = s def onPull(): Unit = f(state) match { case Some((newState, v)) => { @@ -91,8 +91,8 @@ private[pekko] final class UnfoldJava[S, E](s: S, f: function.Function[S, Option override def initialAttributes: Attributes = DefaultAttributes.unfoldAsync override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler { - private[this] var state = s - private[this] var asyncHandler: Try[Option[(S, E)]] => Unit = _ + private var state = s + private var asyncHandler: Try[Option[(S, E)]] => Unit = _ override def preStart(): Unit = { asyncHandler = getAsyncCallback[Try[Option[(S, E)]]](handle).invoke @@ -135,8 +135,8 @@ private[pekko] final class UnfoldJava[S, E](s: S, f: function.Function[S, Option override def initialAttributes: Attributes = DefaultAttributes.unfoldAsync override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler { - private[this] var state = s - private[this] var asyncHandler: Try[Optional[Pair[S, E]]] => Unit = _ + private var state = s + private var asyncHandler: Try[Optional[Pair[S, E]]] => Unit = _ override def preStart(): Unit = { asyncHandler = getAsyncCallback[Try[Optional[Pair[S, E]]]](handle).invoke diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreter.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreter.scala index 61eb9b8a293..a7156ff29ec 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreter.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreter.scala @@ -403,7 +403,7 @@ import org.reactivestreams.Subscription private var downstreamDemand: Long = 0L // This flag is only used if complete/fail is called externally since this op turns into a Finished one inside the // interpreter (i.e. inside this op this flag has no effects since if it is completed the op will not be invoked) - private[this] var downstreamCompletionCause: Option[Throwable] = None + private var downstreamCompletionCause: Option[Throwable] = None def downstreamCompleted: Boolean = downstreamCompletionCause.isDefined // when upstream failed before we got the exposed publisher diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/AggregateWithBoundary.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/AggregateWithBoundary.scala index 79b547c4db4..7d886a8ed09 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/AggregateWithBoundary.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/AggregateWithBoundary.scala @@ -42,7 +42,7 @@ private[pekko] final case class AggregateWithBoundary[In, Agg, Out]( override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new TimerGraphStageLogic(shape) with InHandler with OutHandler { - private[this] var aggregated: Agg = null.asInstanceOf[Agg] + private var aggregated: Agg = null.asInstanceOf[Agg] override def preStart(): Unit = { emitOnTimer.foreach { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreter.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreter.scala index aedcd0b301a..edaa45f31f8 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreter.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreter.scala @@ -225,7 +225,7 @@ import pekko.stream.stage._ val context: ActorRef) { import GraphInterpreter._ - private[this] val ChaseLimit = if (fuzzingMode) 0 else 16 + private val ChaseLimit = if (fuzzingMode) 0 else 16 /** * INTERNAL API @@ -234,35 +234,35 @@ import pekko.stream.stage._ // The number of currently running stages. Once this counter reaches zero, the interpreter is considered to be // completed - private[this] var runningStages = logics.length + private var runningStages = logics.length // Counts how many active connections a stage has. Once it reaches zero, the stage is automatically stopped. - private[this] val shutdownCounter = Array.tabulate(logics.length) { i => + private val shutdownCounter = Array.tabulate(logics.length) { i => logics(i).handlers.length } // Marks whether a stage has been finalized (finalizeStage been called) or not - private[this] val finalizedMark = Array.fill(logics.length)(false) + private val finalizedMark = Array.fill(logics.length)(false) - private[this] var _subFusingMaterializer: Materializer = _ - private[this] lazy val defaultErrorReportingLogLevel = LogLevels.defaultErrorLevel(materializer.system) + private var _subFusingMaterializer: Materializer = _ + private lazy val defaultErrorReportingLogLevel = LogLevels.defaultErrorLevel(materializer.system) def subFusingMaterializer: Materializer = _subFusingMaterializer // An event queue implemented as a circular buffer // FIXME: This calculates the maximum size ever needed, but most assemblies can run on a smaller queue - private[this] val eventQueue = new Array[Connection](1 << (32 - Integer.numberOfLeadingZeros(connections.length - 1))) - private[this] val mask = eventQueue.length - 1 - private[this] var queueHead: Int = 0 - private[this] var queueTail: Int = 0 - - private[this] var chaseCounter = 0 // the first events in preStart blocks should be not chased - private[this] var chasedPush: Connection = NoEvent - private[this] var chasedPull: Connection = NoEvent + private val eventQueue = new Array[Connection](1 << (32 - Integer.numberOfLeadingZeros(connections.length - 1))) + private val mask = eventQueue.length - 1 + private var queueHead: Int = 0 + private var queueTail: Int = 0 + + private var chaseCounter = 0 // the first events in preStart blocks should be not chased + private var chasedPush: Connection = NoEvent + private var chasedPull: Connection = NoEvent // Set whenever a stage's shutdownCounter transitions to 0 (i.e. the stage just became completed and // needs finalization). Lets the chase / dispatch loops skip the per-iteration shutdownCounter array // load in afterStageHasRun when no stage has completed since the last finalization pass. - private[this] var pendingFinalization: Boolean = false + private var pendingFinalization: Boolean = false private def queueStatus: String = { val contents = (queueHead until queueTail).map(idx => { @@ -271,7 +271,7 @@ import pekko.stream.stage._ }) s"(${eventQueue.length}, $queueHead, $queueTail)(${contents.mkString(", ")})" } - private[this] var _Name: String = _ + private var _Name: String = _ def Name: String = if (_Name eq null) { _Name = f"${System.identityHashCode(this)}%08X" diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/IteratorSource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/IteratorSource.scala index 7c6baa51145..8877586c8c1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/IteratorSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/IteratorSource.scala @@ -21,8 +21,8 @@ import scala.util.control.NonFatal import org.apache.pekko import pekko.annotation.InternalApi -import pekko.stream.ActorAttributes.SupervisionStrategy import pekko.stream.{ Attributes, Outlet, SourceShape, Supervision } +import pekko.stream.ActorAttributes.SupervisionStrategy import pekko.stream.impl.fusing.GraphStages.ValuePresentedSource import pekko.stream.stage.{ GraphStage, GraphStageLogic, OutHandler } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/Ops.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/Ops.scala index ba21468469a..50ad7523de3 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/Ops.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/Ops.scala @@ -1422,7 +1422,7 @@ private[stream] object Collect { private var buffer: BufferImpl[Out] = _ private val invokeFutureCB: Try[Out] => Unit = getAsyncCallback(futureCompleted).invoke - private[this] def todo: Int = inFlight + buffer.used + private def todo: Int = inFlight + buffer.used override def preStart(): Unit = buffer = BufferImpl(parallelism, inheritedAttributes) @@ -1527,7 +1527,8 @@ private[stream] object Collect { log = logAdapter match { case Some(l) => l case _ => - Logging(materializer.system, materializer)(fromMaterializer) + implicit val ls: LogSource[Materializer] = fromMaterializer + Logging(materializer.system, materializer) } } @@ -1647,7 +1648,8 @@ private[stream] object Collect { log = logAdapter match { case Some(l) => l case _ => - Logging.withMarker(materializer.system, materializer)(fromMaterializer) + implicit val ls: LogSource[Materializer] = fromMaterializer + Logging.withMarker(materializer.system, materializer) } } @@ -1920,14 +1922,14 @@ private[stream] object Collect { new TimerGraphStageLogic(shape) with InHandler with OutHandler { import Delay._ - private[this] val size = inheritedAttributes.mandatoryAttribute[InputBuffer].max + private val size = inheritedAttributes.mandatoryAttribute[InputBuffer].max - private[this] val delayStrategy = delayStrategySupplier() + private val delayStrategy = delayStrategySupplier() // buffer has pairs of timestamp of expected push and element - private[this] val buffer = BufferImpl[(Long, T)](size, inheritedAttributes) + private val buffer = BufferImpl[(Long, T)](size, inheritedAttributes) - private[this] val onPushWhenBufferFull: () => Unit = overflowStrategy match { + private val onPushWhenBufferFull: () => Unit = overflowStrategy match { case EmitEarly => () => { if (isAvailable(out)) { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/RangeSource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/RangeSource.scala index 4e9cad700e9..e8078e38545 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/RangeSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/RangeSource.scala @@ -36,14 +36,14 @@ private[pekko] final class RangeSource[T](val range: immutable.Range, defaultAtt private val out = Outlet[T]("RangeSource.out") override val shape: SourceShape[T] = SourceShape(out) - private[this] val isEmptyRange = range.isEmpty - private[this] val rangeStart = range.start - private[this] val rangeLast = if (isEmptyRange) 0 else range.last - private[this] val rangeStep = range.step + private val isEmptyRange = range.isEmpty + private val rangeStart = range.start + private val rangeLast = if (isEmptyRange) 0 else range.last + private val rangeStep = range.step override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler { - private[this] var nextElement = rangeStart + private var nextElement = rangeStart override def preStart(): Unit = if (isEmptyRange) completeStage() diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/StreamOfStreams.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/StreamOfStreams.scala index 1d7ffff8b45..882e717f5d9 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/StreamOfStreams.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/StreamOfStreams.scala @@ -851,7 +851,7 @@ import pekko.util.OptionVal override def createLogic(attr: Attributes) = new GraphStageLogic(shape) with InHandler { // check for previous materialization eagerly so we fail with a more useful stacktrace - private[this] val materializationException: OptionVal[IllegalStateException] = + private val materializationException: OptionVal[IllegalStateException] = if (status.get.isInstanceOf[AsyncCallback[?]]) OptionVal.Some(createMaterializedTwiceException()) else @@ -946,7 +946,7 @@ import pekko.util.OptionVal override def createLogic(inheritedAttributes: Attributes) = new GraphStageLogic(shape) with OutHandler { // check for previous materialization eagerly so we fail with a more useful stacktrace - private[this] val materializationException: OptionVal[IllegalStateException] = + private val materializationException: OptionVal[IllegalStateException] = if (status.get.isInstanceOf[AsyncCallback[?]]) OptionVal.Some(createMaterializedTwiceException()) else diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/ByteStringParser.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/ByteStringParser.scala index bef6e0e7d41..bd818670260 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/ByteStringParser.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/ByteStringParser.scala @@ -191,7 +191,7 @@ import pekko.util.ByteString class ByteReader(input: ByteString) { - private[this] var off = 0 + private var off = 0 def hasRemaining: Boolean = off < input.length def remainingSize: Int = input.length - off diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSinkStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSinkStage.scala index 5e6be230fdd..4b35eeec905 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSinkStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSinkStage.scala @@ -25,7 +25,17 @@ import pekko.annotation.InternalApi import pekko.stream.{ AbruptStageTerminationException, Attributes, Inlet, SinkShape } import pekko.stream.Attributes.InputBuffer import pekko.stream.impl.Stages.DefaultAttributes -import pekko.stream.impl.io.InputStreamSinkStage._ +import pekko.stream.impl.io.InputStreamSinkStage.{ + AdapterToStageMessage, + Close, + Data, + Failed, + Finished, + Initialized, + ReadElementAcknowledgement, + StageWithCallback, + StreamToAdapterMessage +} import pekko.stream.stage._ import pekko.util.ByteString @@ -135,7 +145,7 @@ private[stream] object InputStreamSinkStage { var detachedChunk: Option[ByteString] = None @scala.throws(classOf[IOException]) - private[this] def executeIfNotClosed[T](f: () => T): T = + private def executeIfNotClosed[T](f: () => T): T = if (isActive.get()) { waitIfNotInitialized() f() @@ -190,7 +200,7 @@ private[stream] object InputStreamSinkStage { } else -1) } - private[this] def readBytes(a: Array[Byte], begin: Int, length: Int): Int = { + private def readBytes(a: Array[Byte], begin: Int, length: Int): Int = { require(detachedChunk.nonEmpty, "Chunk must be pulled from shared buffer") val availableInChunk = detachedChunk.get.size val readBytes = getData(a, begin, length, 0) @@ -207,7 +217,7 @@ private[stream] object InputStreamSinkStage { } @tailrec - private[this] def getData(arr: Array[Byte], begin: Int, length: Int, gotBytes: Int): Int = { + private def getData(arr: Array[Byte], begin: Int, length: Int, gotBytes: Int): Int = { grabDataChunk() match { case Some(data) => val size = data.size @@ -227,7 +237,7 @@ private[stream] object InputStreamSinkStage { } } - private[this] def waitIfNotInitialized(): Unit = { + private def waitIfNotInitialized(): Unit = { if (!isInitialized) { sharedBuffer.poll(readTimeout.toMillis, TimeUnit.MILLISECONDS) match { case Initialized => isInitialized = true @@ -237,7 +247,7 @@ private[stream] object InputStreamSinkStage { } } - private[this] def grabDataChunk(): Option[ByteString] = { + private def grabDataChunk(): Option[ByteString] = { detachedChunk match { case None => sharedBuffer.poll() match { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamSourceStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamSourceStage.scala index d0dbb81c27e..93c816998ba 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamSourceStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamSourceStage.scala @@ -24,7 +24,7 @@ import org.apache.pekko import pekko.stream.{ Attributes, Outlet, SourceShape } import pekko.stream.Attributes.InputBuffer import pekko.stream.impl.Stages.DefaultAttributes -import pekko.stream.impl.io.OutputStreamSourceStage._ +import pekko.stream.impl.io.OutputStreamSourceStage.{ AdapterToStageMessage, Close, Send } import pekko.stream.stage._ import pekko.util.ByteString @@ -81,7 +81,7 @@ private[pekko] class OutputStreamAdapter( extends OutputStream { @scala.throws(classOf[IOException]) - private[this] def sendData(data: ByteString): Unit = { + private def sendData(data: ByteString): Unit = { if (!unfulfilledDemand.tryAcquire(writeTimeout.toMillis, TimeUnit.MILLISECONDS)) { throw new IOException("Timed out trying to write data to stream") } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/DeflateDecompressorBase.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/DeflateDecompressorBase.scala index 8c523fd4c23..922bdf7ba91 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/DeflateDecompressorBase.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/DeflateDecompressorBase.scala @@ -37,7 +37,7 @@ import pekko.util.ByteString * buffer around avoids reallocating a buffer that may be too big in many * cases for every call of `parse`. */ - private[this] val buffer = new Array[Byte](maxBytesPerChunk) + private val buffer = new Array[Byte](maxBytesPerChunk) abstract class Inflate(noPostProcessing: Boolean) extends ParseStep[ByteString] { override def canWorkWithPartialData = true diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SinkRefImpl.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SinkRefImpl.scala index 67121c74214..53b8a89c8d1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SinkRefImpl.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SinkRefImpl.scala @@ -71,11 +71,11 @@ private[stream] final class SinkRefStageImpl[In] private[pekko] (val initialPart val logic = new TimerGraphStageLogic(shape) with StageLogging with ActorRefStage with InHandler { override protected def logSource: Class[?] = classOf[SinkRefStageImpl[?]] - private[this] val streamRefsMaster = StreamRefsMaster(eagerMaterializer.system) + private val streamRefsMaster = StreamRefsMaster(eagerMaterializer.system) // settings --- @nowarn("msg=deprecated") // can't remove this settings access without breaking compat - private[this] val subscriptionTimeout = { + private val subscriptionTimeout = { import StreamRefAttributes._ val settings = eagerMaterializer.settings.streamRefSettings inheritedAttributes.get[StreamRefAttributes.SubscriptionTimeout]( @@ -83,7 +83,7 @@ private[stream] final class SinkRefStageImpl[In] private[pekko] (val initialPart } @nowarn("msg=deprecated") // can't remove this settings access without breaking compat - private[this] val finalTerminationSignalDeadline = { + private val finalTerminationSignalDeadline = { import StreamRefAttributes._ val settings = eagerMaterializer.settings.streamRefSettings inheritedAttributes @@ -94,7 +94,7 @@ private[stream] final class SinkRefStageImpl[In] private[pekko] (val initialPart // end of settings --- override protected val stageActorName: String = streamRefsMaster.nextSinkRefStageName() - private[this] val self: GraphStageLogic.StageActor = + private val self: GraphStageLogic.StageActor = getEagerStageActor(eagerMaterializer)(initialReceive) override val ref: ActorRef = self.ref implicit def selfSender: ActorRef = ref @@ -119,7 +119,7 @@ private[stream] final class SinkRefStageImpl[In] private[pekko] (val initialPart // When this side of the stream has completed/failed, and we await the Terminated() signal back from the partner // so we can safely shut down completely; This is to avoid *our* Terminated() signal to reach the partner before the // Complete/Fail message does, which can happen on transports such as Artery which use a dedicated lane for system messages (Terminated) - private[this] var finishedWithAwaitingPartnerTermination: OptionVal[Try[Done]] = OptionVal.None + private var finishedWithAwaitingPartnerTermination: OptionVal[Try[Done]] = OptionVal.None override def preStart(): Unit = { initialPartnerRef match { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SourceRefImpl.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SourceRefImpl.scala index f5cf889272c..4e392cc35b5 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SourceRefImpl.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SourceRefImpl.scala @@ -130,29 +130,29 @@ private[stream] final class SourceRefStageImpl[Out](val initialPartnerRef: Optio val logic = new TimerGraphStageLogic(shape) with StageLogging with ActorRefStage with OutHandler { override protected def logSource: Class[?] = classOf[SourceRefStageImpl[?]] - private[this] val streamRefsMaster = StreamRefsMaster(eagerMaterializer.system) + private val streamRefsMaster = StreamRefsMaster(eagerMaterializer.system) // settings --- import StreamRefAttributes._ @nowarn("msg=deprecated") // can't remove this settings access without breaking compat - private[this] val settings = eagerMaterializer.settings.streamRefSettings + private val settings = eagerMaterializer.settings.streamRefSettings @nowarn("msg=deprecated") // can't remove this settings access without breaking compat - private[this] val subscriptionTimeout = inheritedAttributes.get[StreamRefAttributes.SubscriptionTimeout]( + private val subscriptionTimeout = inheritedAttributes.get[StreamRefAttributes.SubscriptionTimeout]( SubscriptionTimeout(settings.subscriptionTimeout)) @nowarn("msg=deprecated") // can't remove this settings access without breaking compat - private[this] val bufferCapacity = inheritedAttributes + private val bufferCapacity = inheritedAttributes .get[StreamRefAttributes.BufferCapacity](StreamRefAttributes.BufferCapacity(settings.bufferCapacity)) .capacity @nowarn("msg=deprecated") // can't remove this settings access without breaking compat - private[this] val demandRedeliveryInterval = inheritedAttributes + private val demandRedeliveryInterval = inheritedAttributes .get[StreamRefAttributes.DemandRedeliveryInterval](DemandRedeliveryInterval(settings.demandRedeliveryInterval)) .timeout @nowarn("msg=deprecated") // can't remove this settings access without breaking compat - private[this] val finalTerminationSignalDeadline = + private val finalTerminationSignalDeadline = inheritedAttributes .get[StreamRefAttributes.FinalTerminationSignalDeadline]( FinalTerminationSignalDeadline(settings.finalTerminationSignalDeadline)) @@ -160,10 +160,10 @@ private[stream] final class SourceRefStageImpl[Out](val initialPartnerRef: Optio // end of settings --- override protected val stageActorName: String = streamRefsMaster.nextSourceRefStageName() - private[this] val self: GraphStageLogic.StageActor = + private val self: GraphStageLogic.StageActor = getEagerStageActor(eagerMaterializer)(receiveRemoteMessage) override val ref: ActorRef = self.ref - private[this] implicit def selfSender: ActorRef = ref + private implicit def selfSender: ActorRef = ref // demand management --- private var state: State = initialPartnerRef match { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/StreamRefsMaster.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/StreamRefsMaster.scala index f2be78e2069..0bd307f85e2 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/StreamRefsMaster.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/StreamRefsMaster.scala @@ -36,8 +36,8 @@ private[stream] object StreamRefsMaster extends ExtensionId[StreamRefsMaster] wi @InternalApi private[stream] final class StreamRefsMaster extends Extension { - private[this] val sourceRefStageNames = SeqActorName("SourceRef") // "local target" - private[this] val sinkRefStageNames = SeqActorName("SinkRef") // "remote sender" + private val sourceRefStageNames = SeqActorName("SourceRef") // "local target" + private val sinkRefStageNames = SeqActorName("SinkRef") // "remote sender" // TODO introduce a master with which all stages running the streams register themselves? diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/BidiFlow.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/BidiFlow.scala index cc9931759ee..b7e0c9b2dd5 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/BidiFlow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/BidiFlow.scala @@ -20,7 +20,7 @@ import pekko.stream._ object BidiFlow { - private[this] val _identity: BidiFlow[Object, Object, Object, Object, NotUsed] = + private val _identity: BidiFlow[Object, Object, Object, Object, NotUsed] = BidiFlow.fromFlows(Flow.of(classOf[Object]), Flow.of(classOf[Object])) def identity[A, B]: BidiFlow[A, A, B, B, NotUsed] = _identity.asInstanceOf[BidiFlow[A, A, B, B, NotUsed]] diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/DelayStrategy.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/DelayStrategy.scala index 993b0c81a2c..9f4addc0a84 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/DelayStrategy.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/DelayStrategy.scala @@ -93,7 +93,7 @@ object DelayStrategy { new DelayStrategy[T] { - private[this] var delay = initialDelay + private var delay = initialDelay override def nextDelay(elem: T): java.time.Duration = { if (needsIncrease(elem)) { diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Flow.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Flow.scala index 183168136c8..5a889b61899 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Flow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Flow.scala @@ -28,6 +28,8 @@ import scala.jdk.OptionConverters._ import scala.reflect.ClassTag import scala.util.control.NonFatal +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.Done import pekko.NotUsed @@ -43,7 +45,6 @@ import pekko.stream.impl.fusing.{ StatefulMapConcat, ZipWithIndexJava } import pekko.util.ConstantFun import pekko.util.Timeout -import org.jspecify.annotations.Nullable import org.reactivestreams.Processor object Flow { diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/FlowWithContext.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/FlowWithContext.scala index 00675baa843..904cd205df5 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/FlowWithContext.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/FlowWithContext.scala @@ -22,6 +22,8 @@ import scala.jdk.DurationConverters._ import scala.jdk.FutureConverters._ import scala.jdk.OptionConverters._ +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.annotation.ApiMayChange import pekko.event.{ LogMarker, LoggingAdapter, MarkerLoggingAdapter } @@ -29,8 +31,6 @@ import pekko.japi.{ function, Pair } import pekko.stream._ import pekko.util.ConstantFun -import org.jspecify.annotations.Nullable - object FlowWithContext { def create[In, Ctx](): FlowWithContext[In, Ctx, In, Ctx, pekko.NotUsed] = @@ -428,7 +428,7 @@ final class FlowWithContext[In, CtxIn, Out, CtxOut, +Mat]( .map { case (i, c) => Pair(i, c) } .viaMat(delegate.asScala.map(_.toScala))(scaladsl.Keep.right)) - private[this] def viaScala[In2, CtxIn2, Out2, CtxOut2, Mat2]( + private def viaScala[In2, CtxIn2, Out2, CtxOut2, Mat2]( f: scaladsl.FlowWithContext[In, CtxIn, Out, CtxOut, Mat] => scaladsl.FlowWithContext[ In2, CtxIn2, Out2, CtxOut2, Mat2]): FlowWithContext[In2, CtxIn2, Out2, CtxOut2, Mat2] = f(this.asScala).asJava diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Graph.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Graph.scala index 0a919fde2a1..ba9264a8b91 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Graph.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Graph.scala @@ -479,7 +479,7 @@ object Zip { def create[A, B]: Graph[FanInShape2[A, B, A Pair B], NotUsed] = ZipWith.create(_toPair.asInstanceOf[Function2[A, B, A Pair B]]) - private[this] final val _toPair: Function2[Any, Any, Any Pair Any] = (a: Any, b: Any) => new Pair(a, b) + private final val _toPair: Function2[Any, Any, Any Pair Any] = (a: Any, b: Any) => new Pair(a, b) } /** @@ -507,7 +507,7 @@ object ZipLatest { def create[A, B]: Graph[FanInShape2[A, B, A Pair B], NotUsed] = ZipLatestWith.create(_toPair.asInstanceOf[Function2[A, B, A Pair B]]) - private[this] final val _toPair: Function2[Any, Any, Any Pair Any] = (a: Any, b: Any) => new Pair(a, b) + private final val _toPair: Function2[Any, Any, Any Pair Any] = (a: Any, b: Any) => new Pair(a, b) } /** diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Sink.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Sink.scala index 588518cd61f..f9baca42ec6 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Sink.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Sink.scala @@ -24,6 +24,8 @@ import scala.jdk.FutureConverters._ import scala.jdk.OptionConverters._ import scala.util.Try +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko._ import pekko.actor.{ ActorRef, ClassicActorSystemProvider, Status } @@ -34,7 +36,6 @@ import pekko.stream.impl.LinearTraversalBuilder import pekko.stream.scaladsl.SinkToCompletionStage import pekko.util.ConstantFun.scalaAnyToUnit -import org.jspecify.annotations.Nullable import org.reactivestreams.{ Publisher, Subscriber } /** Java API */ diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Source.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Source.scala index e60a445e62c..e3f2add4f4a 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Source.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Source.scala @@ -20,8 +20,8 @@ import java.util.concurrent.{ CompletableFuture, CompletionStage } import scala.annotation.{ nowarn, varargs } import scala.annotation.unchecked.uncheckedVariance import scala.collection.immutable -import scala.concurrent.Promise import scala.concurrent.ExecutionContext +import scala.concurrent.Promise import scala.jdk.CollectionConverters._ import scala.jdk.DurationConverters._ import scala.jdk.FutureConverters._ @@ -29,6 +29,8 @@ import scala.jdk.OptionConverters._ import scala.reflect.ClassTag import scala.util.control.NonFatal +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.{ Done, NotUsed } import pekko.actor.{ ActorRef, Cancellable, ClassicActorSystemProvider } @@ -41,12 +43,11 @@ import pekko.stream.impl.Stages.DefaultAttributes import pekko.stream.impl.fusing.{ RangeSource, StatefulMapConcat, ZipWithIndexJava } import pekko.util._ -import org.jspecify.annotations.Nullable import org.reactivestreams.{ Publisher, Subscriber } /** Java API */ object Source { - private[this] val _empty = new Source[Any, NotUsed](scaladsl.Source.empty) + private val _empty = new Source[Any, NotUsed](scaladsl.Source.empty) /** * Create a `Source` with no elements, i.e. an empty stream that is completed immediately diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SourceWithContext.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SourceWithContext.scala index f0593e4420e..262f6deb800 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SourceWithContext.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SourceWithContext.scala @@ -22,6 +22,8 @@ import scala.jdk.DurationConverters._ import scala.jdk.FutureConverters._ import scala.jdk.OptionConverters._ +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.actor.ClassicActorSystemProvider import pekko.annotation.ApiMayChange @@ -31,8 +33,6 @@ import pekko.japi.function import pekko.stream._ import pekko.util.ConstantFun -import org.jspecify.annotations.Nullable - object SourceWithContext { /** @@ -445,7 +445,7 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon def asScala: scaladsl.SourceWithContext[Out, Ctx, Mat] = delegate - private[this] def viaScala[Out2, Ctx2, Mat2]( + private def viaScala[Out2, Ctx2, Mat2]( f: scaladsl.SourceWithContext[Out, Ctx, Mat] => scaladsl.SourceWithContext[Out2, Ctx2, Mat2]) : SourceWithContext[Out2, Ctx2, Mat2] = new SourceWithContext(f(delegate)) diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubFlow.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubFlow.scala index e9f12da74b2..0082bf73d55 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubFlow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubFlow.scala @@ -26,6 +26,8 @@ import scala.jdk.OptionConverters._ import scala.reflect.ClassTag import scala.util.control.NonFatal +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.NotUsed import pekko.event.{ LogMarker, LoggingAdapter, MarkerLoggingAdapter } @@ -35,8 +37,6 @@ import pekko.stream.impl.Stages.DefaultAttributes import pekko.stream.impl.fusing.{ StatefulMapConcat, ZipWithIndexJava } import pekko.util.ConstantFun -import org.jspecify.annotations.Nullable - object SubFlow { /** diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubSource.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubSource.scala index cc8d6b5bb81..18ad5712bc1 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubSource.scala @@ -26,6 +26,8 @@ import scala.jdk.OptionConverters._ import scala.reflect.ClassTag import scala.util.control.NonFatal +import org.jspecify.annotations.Nullable + import org.apache.pekko import pekko.NotUsed import pekko.event.{ LogMarker, LoggingAdapter, MarkerLoggingAdapter } @@ -35,8 +37,6 @@ import pekko.stream.impl.Stages.DefaultAttributes import pekko.stream.impl.fusing.{ StatefulMapConcat, ZipWithIndexJava } import pekko.util.ConstantFun -import org.jspecify.annotations.Nullable - /** * * Upcast a stream of elements to a stream of supertypes of that element. Useful in combination with * fan-in operators where you do not want to pay the cost of casting each element in a `map`. diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Tcp.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Tcp.scala index 2fe12dd0d88..70c47793bb5 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Tcp.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Tcp.scala @@ -36,13 +36,13 @@ import pekko.actor.ExtensionId import pekko.actor.ExtensionIdProvider import pekko.annotation.InternalApi import pekko.io.Inet.SocketOption +import pekko.japi.Util.immutableSeq import pekko.japi.function import pekko.stream.Materializer import pekko.stream.SystemMaterializer import pekko.stream.TLSClosing import pekko.stream.scaladsl import pekko.util.ByteString -import pekko.japi.Util.immutableSeq object Tcp extends ExtensionId[Tcp] with ExtensionIdProvider { diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/BidiFlow.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/BidiFlow.scala index 9b84b0af80d..47598bf82c3 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/BidiFlow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/BidiFlow.scala @@ -234,7 +234,7 @@ final class BidiFlow[-I1, +O1, -I2, +O2, +Mat]( } object BidiFlow { - private[this] val _identity: BidiFlow[Any, Any, Any, Any, NotUsed] = + private val _identity: BidiFlow[Any, Any, Any, Any, NotUsed] = BidiFlow.fromFlows(Flow[Any], Flow[Any]) def identity[A, B]: BidiFlow[A, A, B, B, NotUsed] = _identity.asInstanceOf[BidiFlow[A, A, B, B, NotUsed]] diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/DelayStrategy.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/DelayStrategy.scala index 549a1583948..1323c344e77 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/DelayStrategy.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/DelayStrategy.scala @@ -58,7 +58,7 @@ object DelayStrategy { new DelayStrategy[T] { - private[this] var delay: FiniteDuration = initialDelay + private var delay: FiniteDuration = initialDelay override def nextDelay(elem: T): FiniteDuration = { if (needsIncrease(elem)) { diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Flow.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Flow.scala index 59e524fc4cd..4ae16e46ce4 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Flow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Flow.scala @@ -428,7 +428,7 @@ object Flow { private[stream] val identityTraversalBuilder = LinearTraversalBuilder.fromBuilder(GraphStages.identity.traversalBuilder, GraphStages.identity.shape, Keep.right) - private[this] val identity: Flow[Any, Any, NotUsed] = + private val identity: Flow[Any, Any, NotUsed] = new Flow[Any, Any, NotUsed](identityTraversalBuilder, GraphStages.identity.shape) /** diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Graph.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Graph.scala index 16b9a605c0c..6cde3ffa9f2 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Graph.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Graph.scala @@ -1415,8 +1415,8 @@ private[stream] final class OrElse[T] override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler with InHandler { - private[this] var currentIn = primary - private[this] var primaryPushed = false + private var currentIn = primary + private var primaryPushed = false override def onPull(): Unit = { pull(currentIn) diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Hub.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Hub.scala index 4b6ca0063ec..bf05d761d9b 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Hub.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Hub.scala @@ -146,7 +146,7 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo override val shape: SourceShape[T] = SourceShape(out) // Half of buffer size, rounded up - private[this] val DemandThreshold = (perProducerBufferSize / 2) + (perProducerBufferSize % 2) + private val DemandThreshold = (perProducerBufferSize / 2) + (perProducerBufferSize % 2) private sealed trait Event { def id: Long @@ -180,12 +180,12 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo * processing of control messages. This causes no issues though, see the explanation in 'tryProcessNext'. */ private val queue = new AbstractNodeQueue[Event] {} - @volatile private[this] var needWakeup = false - @volatile private[this] var shuttingDown = false - @volatile private[this] var draining = false + @volatile private var needWakeup = false + @volatile private var shuttingDown = false + @volatile private var draining = false - private[this] val demands = scala.collection.mutable.LongMap.empty[InputState] - private[this] val wakeupCallback = getAsyncCallback[NotUsed](_ => + private val demands = scala.collection.mutable.LongMap.empty[InputState] + private val wakeupCallback = getAsyncCallback[NotUsed](_ => // We are only allowed to dequeue if we are not backpressured. See comment in tryProcessNext() for details. if (isAvailable(out)) tryProcessNext(firstAttempt = true)) @@ -319,8 +319,8 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo new GraphStageLogic(shape) with InHandler { // Start from non-zero demand to avoid initial delays. // The HUB will expect this behavior. - private[this] var demand: Long = perProducerBufferSize - private[this] val id = idCounter.getAndIncrement() + private var demand: Long = perProducerBufferSize + private val id = idCounter.getAndIncrement() override def preStart(): Unit = { if (!logic.isDraining && !logic.isShuttingDown) { @@ -495,7 +495,7 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I override val shape: SinkShape[T] = SinkShape(in) // Half of buffer size, rounded up - private[this] val DemandThreshold = (bufferSize / 2) + (bufferSize % 2) + private val DemandThreshold = (bufferSize / 2) + (bufferSize % 2) private sealed trait HubEvent @@ -515,22 +515,22 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I private class BroadcastSinkLogic(_shape: Shape) extends GraphStageLogic(_shape) with InHandler { - private[this] val callbackPromise: Promise[AsyncCallback[HubEvent]] = Promise() - private[this] val noRegistrationsState = Open(callbackPromise.future, Nil) + private val callbackPromise: Promise[AsyncCallback[HubEvent]] = Promise() + private val noRegistrationsState = Open(callbackPromise.future, Nil) val state = new AtomicReference[HubState](noRegistrationsState) private var initialized = false // Start from values that will almost immediately overflow. This has no effect on performance, any starting // number will do, however, this protects from regressions as these values *almost surely* overflow and fail // tests if someone makes a mistake. - @volatile private[this] var tail = Int.MaxValue - private[this] var head = Int.MaxValue + @volatile private var tail = Int.MaxValue + private var head = Int.MaxValue /* * An Array with a published tail ("latest message") and a privately maintained head ("earliest buffered message"). * Elements are published by simply putting them into the array and bumping the tail. If necessary, certain * consumers are sent a wakeup message through an AsyncCallback. */ - private[this] val queue = new Array[AnyRef](bufferSize) + private val queue = new Array[AnyRef](bufferSize) /* This is basically a classic Bucket Queue: https://en.wikipedia.org/wiki/Bucket_queue * (in fact, this is the variant described in the Optimizations section, where the given set * of priorities always fall to a range @@ -542,9 +542,9 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I * a wakeup and update their position at the same time. * */ - private[this] val consumerWheel = + private val consumerWheel = Array.fill[java.util.ArrayList[Consumer]](bufferSize * 2)(new util.ArrayList[Consumer]()) - private[this] var activeConsumers = 0 + private var activeConsumers = 0 override def preStart(): Unit = { setKeepGoing(true) @@ -786,10 +786,10 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with OutHandler { - private[this] var untilNextAdvanceSignal = DemandThreshold - private[this] val id = idCounter.getAndIncrement() - private[this] var offsetInitialized = false - private[this] var hubCallback: AsyncCallback[HubEvent] = _ + private var untilNextAdvanceSignal = DemandThreshold + private val id = idCounter.getAndIncrement() + private var offsetInitialized = false + private var hubCallback: AsyncCallback[HubEvent] = _ /* * We need to track our last offset that we published to the Hub. The reason is, that for efficiency reasons, @@ -797,8 +797,8 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I * is needed, but it also means that we need to keep track of both our current offset, and the last one that * we published. */ - private[this] var previousPublishedOffset = 0 - private[this] var offset = 0 + private var previousPublishedOffset = 0 + private var offset = 0 override def preStart(): Unit = { val callback = getAsyncCallback(onCommand) diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Sink.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Sink.scala index 2fa336579b6..d4e78bebf94 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Sink.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Sink.scala @@ -319,7 +319,7 @@ object Sink { */ def source[T]: Sink[T, Source[T, NotUsed]] = _sourceSink.asInstanceOf[Sink[T, Source[T, NotUsed]]] - private[this] val _sourceSink = fromGraph(SourceSink) + private val _sourceSink = fromGraph(SourceSink) /** * A `Sink` that will consume the stream and discard the elements. @@ -330,7 +330,7 @@ object Sink { * A [[Sink]] that will always backpressure never cancel and never consume any elements from the stream. */ def never: Sink[Any, Future[Done]] = _never - private[this] val _never: Sink[Any, Future[Done]] = fromGraph(GraphStages.NeverSink) + private val _never: Sink[Any, Future[Done]] = fromGraph(GraphStages.NeverSink) /** * A `Sink` that will invoke the given procedure for each received element. The sink is materialized diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Source.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Source.scala index 39b81555263..4cd4594e1d0 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Source.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Source.scala @@ -575,7 +575,7 @@ object Source { * A `Source` with no elements, i.e. an empty stream that is completed immediately for every connected `Sink`. */ def empty[T]: Source[T, NotUsed] = _empty - private[this] val _empty: Source[Nothing, NotUsed] = + private val _empty: Source[Nothing, NotUsed] = fromGraphStage(EmptySource) /** @@ -616,7 +616,7 @@ object Source { * This stream could be useful in tests. */ def never[T]: Source[T, NotUsed] = _never - private[this] val _never: Source[Nothing, NotUsed] = fromGraphStage(GraphStages.NeverSource) + private val _never: Source[Nothing, NotUsed] = fromGraphStage(GraphStages.NeverSource) /** * Emits a single value when the given `CompletionStage` is successfully completed and then completes the stream. diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/TLS.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/TLS.scala index 57e74f1f26a..f69d8ef577d 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/TLS.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/TLS.scala @@ -17,8 +17,6 @@ import javax.net.ssl.{ SSLContext, SSLEngine, SSLSession } import scala.util.{ Success, Try } -import com.typesafe.config.{ ConfigException, ConfigFactory } - import org.apache.pekko import pekko.NotUsed import pekko.stream._ @@ -26,6 +24,8 @@ import pekko.stream.TLSProtocol._ import pekko.stream.impl.io.{ TlsGraphStage, TlsModule } import pekko.util.ByteString +import com.typesafe.config.{ ConfigException, ConfigFactory } + /** * Stream cipher support based upon JSSE. * diff --git a/stream/src/main/scala/org/apache/pekko/stream/serialization/StreamRefSerializer.scala b/stream/src/main/scala/org/apache/pekko/stream/serialization/StreamRefSerializer.scala index daa66f753c2..5badc9b2a5e 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/serialization/StreamRefSerializer.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/serialization/StreamRefSerializer.scala @@ -30,16 +30,16 @@ private[pekko] final class StreamRefSerializer(val system: ExtendedActorSystem) extends SerializerWithStringManifest with BaseSerializer { - private[this] lazy val serialization = SerializationExtension(system) - - private[this] val SequencedOnNextManifest = "A" - private[this] val CumulativeDemandManifest = "B" - private[this] val RemoteSinkFailureManifest = "C" - private[this] val RemoteSinkCompletedManifest = "D" - private[this] val SourceRefManifest = "E" - private[this] val SinkRefManifest = "F" - private[this] val OnSubscribeHandshakeManifest = "G" - private[this] val AckManifest = "H" + private lazy val serialization = SerializationExtension(system) + + private val SequencedOnNextManifest = "A" + private val CumulativeDemandManifest = "B" + private val RemoteSinkFailureManifest = "C" + private val RemoteSinkCompletedManifest = "D" + private val SourceRefManifest = "E" + private val SinkRefManifest = "F" + private val OnSubscribeHandshakeManifest = "G" + private val AckManifest = "H" override def manifest(o: AnyRef): String = o match { // protocol diff --git a/stream/src/main/scala/org/apache/pekko/stream/stage/GraphStage.scala b/stream/src/main/scala/org/apache/pekko/stream/stage/GraphStage.scala index 8e97e885408..d74ff8e1e10 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/stage/GraphStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/stage/GraphStage.scala @@ -241,7 +241,7 @@ object GraphStageLogic { def ref: ActorRef = functionRef @volatile - private[this] var behavior = initialReceive + private var behavior = initialReceive /** INTERNAL API */ private[pekko] def internalReceive(pack: (ActorRef, Any)): Unit = { @@ -376,7 +376,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: /** * INTERNAL API */ - private[this] var _interpreter: GraphInterpreter = _ + private var _interpreter: GraphInterpreter = _ /** * INTERNAL API diff --git a/stream/src/main/scala/org/apache/pekko/stream/stage/StageLogging.scala b/stream/src/main/scala/org/apache/pekko/stream/stage/StageLogging.scala index dcc12cbd8fb..ff68a4cc871 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/stage/StageLogging.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/stage/StageLogging.scala @@ -30,7 +30,7 @@ import pekko.stream.MaterializerLoggingProvider * these decisions have to be handled by the operator itself. */ trait StageLogging { self: GraphStageLogic => - private[this] var _log: LoggingAdapter = _ + private var _log: LoggingAdapter = _ /** Override to customise reported log source */ protected def logSource: Class[?] = this.getClass diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/CallingThreadDispatcher.scala b/testkit/src/main/scala/org/apache/pekko/testkit/CallingThreadDispatcher.scala index 8a34ecb0d4a..49be17a601e 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/CallingThreadDispatcher.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/CallingThreadDispatcher.scala @@ -362,7 +362,7 @@ class CallingThreadMailbox(_receiver: pekko.actor.Cell, val mailboxType: Mailbox } /** - * This is only a marker to be put in the messageQueue’s stead to make error + * This is only a marker to be put in the messageQueue's stead to make error * messages pertaining to violated mailbox type requirements less cryptic. */ override val messageQueue: MessageQueue = q.get