Adds parentheses to method that has side-effect (#26864)

* Adds parentheses to Thread.currentThread and Lock.lock

* Removes some unnecessary parentheses and fixes typo

* Simplify Map.get(xxx).getOrElse(yyy) to Map.getOrElse(xxx, yyy)

* Adds parentheses to CountDownLatch#countDown

* Removes unnecessary new-modifier of case-class and asInstance cast
This commit is contained in:
Shutao Tang 2019-05-09 00:51:15 +08:00 committed by Patrik Nordwall
parent c74b7391f5
commit fc189e6962
21 changed files with 53 additions and 53 deletions

View file

@ -54,7 +54,7 @@ private[akka] trait AbstractProps {
v.getBounds.collectFirst { case c: Class[_] if ac.isAssignableFrom(c) && c != ac => c }.getOrElse(ac) v.getBounds.collectFirst { case c: Class[_] if ac.isAssignableFrom(c) && c != ac => c }.getOrElse(ac)
case x => throw new IllegalArgumentException(s"unsupported type found in Creator argument [$x]") case x => throw new IllegalArgumentException(s"unsupported type found in Creator argument [$x]")
} }
case c: Class[_] if (c == coc) => case c: Class[_] if c == coc =>
throw new IllegalArgumentException( throw new IllegalArgumentException(
"erased Creator types (e.g. lambdas) are unsupported, use Props.create(actorClass, creator) instead") "erased Creator types (e.g. lambdas) are unsupported, use Props.create(actorClass, creator) instead")
} }

View file

@ -488,7 +488,7 @@ trait Actor {
*/ */
implicit val context: ActorContext = { implicit val context: ActorContext = {
val contextStack = ActorCell.contextStack.get val contextStack = ActorCell.contextStack.get
if ((contextStack.isEmpty) || (contextStack.head eq null)) if (contextStack.isEmpty || (contextStack.head eq null))
throw ActorInitializationException( throw ActorInitializationException(
s"You cannot create an instance of [${getClass.getName}] explicitly using the constructor (new). " + s"You cannot create an instance of [${getClass.getName}] explicitly using the constructor (new). " +
"You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.") "You have to use one of the 'actorOf' factory methods to create a new actor. See the documentation.")

View file

@ -382,7 +382,7 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin
private def addressStringLengthDiff(address: Address): Int = { private def addressStringLengthDiff(address: Address): Int = {
val r = root val r = root
if (r.address.host.isDefined) 0 if (r.address.host.isDefined) 0
else (address.toString.length - r.address.toString.length) else address.toString.length - r.address.toString.length
} }
/** /**

View file

@ -748,7 +748,7 @@ private[akka] final class FunctionRef(
} }
} }
// watching, _watchedBy and maintainAddressTerminatedSubscription requires sychronized access because // watching, _watchedBy and maintainAddressTerminatedSubscription requires synchronized access because
// AddressTerminatedTopic must be updated together with the variables here. // AddressTerminatedTopic must be updated together with the variables here.
// Important: don't include calls to sendSystemMessage inside the synchronized since that can // Important: don't include calls to sendSystemMessage inside the synchronized since that can
// result in deadlock, see issue #26326 // result in deadlock, see issue #26326
@ -948,7 +948,7 @@ private[akka] final class FunctionRef(
// AddressTerminatedTopic update not needed // AddressTerminatedTopic update not needed
block block
case _ => case _ =>
def hasNonLocalAddress: Boolean = (watching.exists(isNonLocal)) || (watchedByOrEmpty.exists(isNonLocal)) def hasNonLocalAddress: Boolean = watching.exists(isNonLocal) || watchedByOrEmpty.exists(isNonLocal)
val had = hasNonLocalAddress val had = hasNonLocalAddress
val result = block val result = block

View file

@ -499,7 +499,7 @@ private[akka] class LocalActorRefProvider private[akka] (
override def getSingleChild(name: String): InternalActorRef = name match { override def getSingleChild(name: String): InternalActorRef = name match {
case "temp" => tempContainer case "temp" => tempContainer
case "deadLetters" => deadLetters case "deadLetters" => deadLetters
case other => extraNames.get(other).getOrElse(super.getSingleChild(other)) case other => extraNames.getOrElse(other, super.getSingleChild(other))
} }
} }

View file

@ -1055,7 +1055,7 @@ private[akka] class ActorSystemImpl(
extensions.replace(ext, inProcessOfRegistration, t) //In case shit hits the fan, remove the inProcess signal extensions.replace(ext, inProcessOfRegistration, t) //In case shit hits the fan, remove the inProcess signal
throw t //Escalate to caller throw t //Escalate to caller
} finally { } finally {
inProcessOfRegistration.countDown //Always notify listeners of the inProcess signal inProcessOfRegistration.countDown() //Always notify listeners of the inProcess signal
} }
case _ => case _ =>
registerExtension(ext) //Someone else is in process of registering an extension for this Extension, retry registerExtension(ext) //Someone else is in process of registering an extension for this Extension, retry

View file

@ -183,7 +183,7 @@ object FSM {
timeout: Option[FiniteDuration] = timeout, timeout: Option[FiniteDuration] = timeout,
stopReason: Option[Reason] = stopReason, stopReason: Option[Reason] = stopReason,
replies: List[Any] = replies): State[S, D] = { replies: List[Any] = replies): State[S, D] = {
new State(stateName, stateData, timeout, stopReason, replies) State(stateName, stateData, timeout, stopReason, replies)
} }
/** /**
@ -461,7 +461,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
if (debugEvent) if (debugEvent)
log.debug("setting " + (if (repeat) "repeating " else "") + "timer '" + name + "'/" + timeout + ": " + msg) log.debug("setting " + (if (repeat) "repeating " else "") + "timer '" + name + "'/" + timeout + ": " + msg)
if (timers contains name) { if (timers contains name) {
timers(name).cancel timers(name).cancel()
} }
val timer = Timer(name, msg, repeat, timerGen.next, this)(context) val timer = Timer(name, msg, repeat, timerGen.next, this)(context)
timer.schedule(self, timeout) timer.schedule(self, timeout)
@ -476,7 +476,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
if (debugEvent) if (debugEvent)
log.debug("canceling timer '" + name + "'") log.debug("canceling timer '" + name + "'")
if (timers contains name) { if (timers contains name) {
timers(name).cancel timers(name).cancel()
timers -= name timers -= name
} }
} }
@ -686,7 +686,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
listeners.remove(actorRef) listeners.remove(actorRef)
case Deafen(actorRef) => case Deafen(actorRef) =>
listeners.remove(actorRef) listeners.remove(actorRef)
case value => { case value =>
if (timeoutFuture.isDefined) { if (timeoutFuture.isDefined) {
timeoutFuture.get.cancel() timeoutFuture.get.cancel()
timeoutFuture = None timeoutFuture = None
@ -694,7 +694,6 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
generation += 1 generation += 1
processMsg(value, sender()) processMsg(value, sender())
} }
}
private def processMsg(value: Any, source: AnyRef): Unit = { private def processMsg(value: Any, source: AnyRef): Unit = {
val event = Event(value, currentState.stateData) val event = Event(value, currentState.stateData)

View file

@ -98,7 +98,7 @@ private[akka] class ArgsReflectConstructor(clz: Class[_ <: Actor], args: immutab
extends IndirectActorProducer { extends IndirectActorProducer {
private[this] val constructor = Reflect.findConstructor(clz, args) private[this] val constructor = Reflect.findConstructor(clz, args)
override def actorClass = clz override def actorClass = clz
override def produce() = Reflect.instantiate(constructor, args).asInstanceOf[Actor] override def produce() = Reflect.instantiate(constructor, args)
} }
/** /**

View file

@ -11,7 +11,7 @@ import scala.annotation.tailrec
import scala.collection.immutable import scala.collection.immutable
import scala.concurrent.{ Await, ExecutionContext, Future, Promise } import scala.concurrent.{ Await, ExecutionContext, Future, Promise }
import scala.concurrent.duration._ import scala.concurrent.duration._
import scala.util.control.{ NonFatal } import scala.util.control.NonFatal
import com.typesafe.config.Config import com.typesafe.config.Config
import akka.event.LoggingAdapter import akka.event.LoggingAdapter
import akka.util.Helpers import akka.util.Helpers
@ -86,7 +86,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac
val sleepMs = if (Helpers.isWindows) (nanos + 4999999) / 10000000 * 10 else (nanos + 999999) / 1000000 val sleepMs = if (Helpers.isWindows) (nanos + 4999999) / 10000000 * 10 else (nanos + 999999) / 1000000
try Thread.sleep(sleepMs) try Thread.sleep(sleepMs)
catch { catch {
case _: InterruptedException => Thread.currentThread.interrupt() // we got woken up case _: InterruptedException => Thread.currentThread().interrupt() // we got woken up
} }
} }
@ -163,11 +163,11 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac
private def schedule(ec: ExecutionContext, r: Runnable, delay: FiniteDuration): TimerTask = private def schedule(ec: ExecutionContext, r: Runnable, delay: FiniteDuration): TimerTask =
if (delay <= Duration.Zero) { if (delay <= Duration.Zero) {
if (stopped.get != null) throw new SchedulerException("cannot enqueue after timer shutdown") if (stopped.get != null) throw SchedulerException("cannot enqueue after timer shutdown")
ec.execute(r) ec.execute(r)
NotCancellable NotCancellable
} else if (stopped.get != null) { } else if (stopped.get != null) {
throw new SchedulerException("cannot enqueue after timer shutdown") throw SchedulerException("cannot enqueue after timer shutdown")
} else { } else {
val delayNanos = delay.toNanos val delayNanos = delay.toNanos
checkMaxDelay(delayNanos) checkMaxDelay(delayNanos)
@ -176,7 +176,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac
val task = new TaskHolder(r, ticks, ec) val task = new TaskHolder(r, ticks, ec)
queue.add(task) queue.add(task)
if (stopped.get != null && task.cancel()) if (stopped.get != null && task.cancel())
throw new SchedulerException("cannot enqueue after timer shutdown") throw SchedulerException("cannot enqueue after timer shutdown")
task task
} }
@ -212,7 +212,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac
case x => collect(q, acc :+ x) case x => collect(q, acc :+ x)
} }
} }
((0 until WheelSize).flatMap(i => collect(wheel(i), Vector.empty))) ++ collect(queue, Vector.empty) (0 until WheelSize).flatMap(i => collect(wheel(i), Vector.empty)) ++ collect(queue, Vector.empty)
} }
@tailrec @tailrec
@ -237,7 +237,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac
checkQueue(time) checkQueue(time)
} }
override final def run = override final def run(): Unit =
try nextTick() try nextTick()
catch { catch {
case t: Throwable => case t: Throwable =>
@ -334,8 +334,8 @@ object LightArrayRevolverScheduler {
executionContext.execute(other) executionContext.execute(other)
true true
} catch { } catch {
case _: InterruptedException => { Thread.currentThread.interrupt(); false } case _: InterruptedException => Thread.currentThread().interrupt(); false
case NonFatal(e) => { executionContext.reportFailure(e); false } case NonFatal(e) => executionContext.reportFailure(e); false
} }
} }

View file

@ -272,7 +272,7 @@ private[akka] class UnstartedCell(
} }
def sendSystemMessage(msg: SystemMessage): Unit = { def sendSystemMessage(msg: SystemMessage): Unit = {
lock.lock // we cannot lose system messages, ever, and we cannot throw an Error from here as well lock.lock() // we cannot lose system messages, ever, and we cannot throw an Error from here as well
try { try {
val cell = self.underlying val cell = self.underlying
if (cellIsReady(cell)) if (cellIsReady(cell))

View file

@ -117,7 +117,7 @@ private[akka] object ChildrenContainer {
override def getByName(name: String): Option[ChildStats] = c.get(name) override def getByName(name: String): Option[ChildStats] = c.get(name)
override def getByRef(actor: ActorRef): Option[ChildRestartStats] = c.get(actor.path.name) match { override def getByRef(actor: ActorRef): Option[ChildRestartStats] = c.get(actor.path.name) match {
case c @ Some(crs: ChildRestartStats) if (crs.child == actor) => c.asInstanceOf[Option[ChildRestartStats]] case c @ Some(crs: ChildRestartStats) if crs.child == actor => c.asInstanceOf[Option[ChildRestartStats]]
case _ => None case _ => None
} }
@ -179,7 +179,7 @@ private[akka] object ChildrenContainer {
override def getByName(name: String): Option[ChildStats] = c.get(name) override def getByName(name: String): Option[ChildStats] = c.get(name)
override def getByRef(actor: ActorRef): Option[ChildRestartStats] = c.get(actor.path.name) match { override def getByRef(actor: ActorRef): Option[ChildRestartStats] = c.get(actor.path.name) match {
case c @ Some(crs: ChildRestartStats) if (crs.child == actor) => c.asInstanceOf[Option[ChildRestartStats]] case c @ Some(crs: ChildRestartStats) if crs.child == actor => c.asInstanceOf[Option[ChildRestartStats]]
case _ => None case _ => None
} }

View file

@ -97,7 +97,7 @@ private[akka] trait DeathWatch { this: ActorCell =>
/** Call only if it was checked before that `watching contains ref` */ /** Call only if it was checked before that `watching contains ref` */
private def checkWatchingSame(ref: InternalActorRef, newMessage: Option[Any]): Unit = { private def checkWatchingSame(ref: InternalActorRef, newMessage: Option[Any]): Unit = {
val previous = watching.get(ref).get val previous = watching(ref)
if (previous != newMessage) if (previous != newMessage)
throw new IllegalStateException( throw new IllegalStateException(
s"Watch($self, $ref) termination message was not overwritten from [$previous] to [$newMessage]. " + s"Watch($self, $ref) termination message was not overwritten from [$previous] to [$newMessage]. " +
@ -105,7 +105,7 @@ private[akka] trait DeathWatch { this: ActorCell =>
} }
protected def tellWatchersWeDied(): Unit = protected def tellWatchersWeDied(): Unit =
if (!watchedBy.isEmpty) { if (watchedBy.nonEmpty) {
try { try {
// Don't need to send to parent parent since it receives a DWN by default // Don't need to send to parent parent since it receives a DWN by default
def sendTerminated(ifLocal: Boolean)(watcher: ActorRef): Unit = def sendTerminated(ifLocal: Boolean)(watcher: ActorRef): Unit =
@ -137,7 +137,7 @@ private[akka] trait DeathWatch { this: ActorCell =>
} }
protected def unwatchWatchedActors(@unused actor: Actor): Unit = protected def unwatchWatchedActors(@unused actor: Actor): Unit =
if (!watching.isEmpty) { if (watching.nonEmpty) {
maintainAddressTerminatedSubscription() { maintainAddressTerminatedSubscription() {
try { try {
watching.foreach { // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ watching.foreach { // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
@ -220,7 +220,7 @@ private[akka] trait DeathWatch { this: ActorCell =>
} }
if (isNonLocal(change)) { if (isNonLocal(change)) {
def hasNonLocalAddress: Boolean = ((watching.keysIterator.exists(isNonLocal)) || (watchedBy.exists(isNonLocal))) def hasNonLocalAddress: Boolean = watching.keysIterator.exists(isNonLocal) || watchedBy.exists(isNonLocal)
val had = hasNonLocalAddress val had = hasNonLocalAddress
val result = block val result = block
val has = hasNonLocalAddress val has = hasNonLocalAddress

View file

@ -120,7 +120,7 @@ private[akka] trait Dispatch { this: ActorCell =>
private def handleException: Catcher[Unit] = { private def handleException: Catcher[Unit] = {
case e: InterruptedException => case e: InterruptedException =>
system.eventStream.publish(Error(e, self.path.toString, clazz(actor), "interrupted during message send")) system.eventStream.publish(Error(e, self.path.toString, clazz(actor), "interrupted during message send"))
Thread.currentThread.interrupt() Thread.currentThread().interrupt()
case NonFatal(e) => case NonFatal(e) =>
val message = e match { val message = e match {
case n: NoStackTrace => "swallowing exception during message send: " + n.getMessage case n: NoStackTrace => "swallowing exception during message send: " + n.getMessage

View file

@ -123,7 +123,7 @@ private[akka] trait FaultHandling { this: ActorCell =>
assert(perpetrator == self) assert(perpetrator == self)
setReceiveTimeout(Duration.Undefined) setReceiveTimeout(Duration.Undefined)
cancelReceiveTimeout cancelReceiveTimeout()
// stop all children, which will turn childrenRefs into TerminatingChildrenContainer (if there are children) // stop all children, which will turn childrenRefs into TerminatingChildrenContainer (if there are children)
children.foreach(stop) children.foreach(stop)
@ -142,7 +142,7 @@ private[akka] trait FaultHandling { this: ActorCell =>
protected def terminate(): Unit = { protected def terminate(): Unit = {
setReceiveTimeout(Duration.Undefined) setReceiveTimeout(Duration.Undefined)
cancelReceiveTimeout cancelReceiveTimeout()
// prevent Deadletter(Terminated) messages // prevent Deadletter(Terminated) messages
unwatchWatchedActors(actor) unwatchWatchedActors(actor)
@ -180,8 +180,8 @@ private[akka] trait FaultHandling { this: ActorCell =>
suspendNonRecursive() suspendNonRecursive()
// suspend children // suspend children
val skip: Set[ActorRef] = currentMessage match { val skip: Set[ActorRef] = currentMessage match {
case Envelope(Failed(_, _, _), child) => { setFailed(child); Set(child) } case Envelope(Failed(_, _, _), child) => setFailed(child); Set(child)
case _ => { setFailed(self); Set.empty } case _ => setFailed(self); Set.empty
} }
suspendChildren(exceptFor = skip ++ childrenNotToSuspend) suspendChildren(exceptFor = skip ++ childrenNotToSuspend)
t match { t match {

View file

@ -31,8 +31,8 @@ private[akka] trait ReceiveTimeout { this: ActorCell =>
checkReceiveTimeout(!message.isInstanceOf[NotInfluenceReceiveTimeout]) checkReceiveTimeout(!message.isInstanceOf[NotInfluenceReceiveTimeout])
final def checkReceiveTimeout(reschedule: Boolean = true): Unit = { final def checkReceiveTimeout(reschedule: Boolean = true): Unit = {
val (recvtimeout, task) = receiveTimeoutData val (recvTimeout, task) = receiveTimeoutData
recvtimeout match { recvTimeout match {
case f: FiniteDuration => case f: FiniteDuration =>
// The fact that timeout is FiniteDuration and task is emptyCancellable // The fact that timeout is FiniteDuration and task is emptyCancellable
// means that a user called `context.setReceiveTimeout(...)` // means that a user called `context.setReceiveTimeout(...)`

View file

@ -52,7 +52,7 @@ object ForkJoinExecutorConfigurator {
Thread.currentThread.interrupt() Thread.currentThread.interrupt()
false false
case anything: Throwable => case anything: Throwable =>
val t = Thread.currentThread val t = Thread.currentThread()
t.getUncaughtExceptionHandler match { t.getUncaughtExceptionHandler match {
case null => case null =>
case some => some.uncaughtException(t, anything) case some => some.uncaughtException(t, anything)

View file

@ -242,10 +242,10 @@ private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
run(); false run(); false
} catch { } catch {
case _: InterruptedException => case _: InterruptedException =>
Thread.currentThread.interrupt() Thread.currentThread().interrupt()
false false
case anything: Throwable => case anything: Throwable =>
val t = Thread.currentThread val t = Thread.currentThread()
t.getUncaughtExceptionHandler match { t.getUncaughtExceptionHandler match {
case null => case null =>
case some => some.uncaughtException(t, anything) case some => some.uncaughtException(t, anything)

View file

@ -709,7 +709,7 @@ object Logging {
* The thread that created this log event * The thread that created this log event
*/ */
@transient @transient
val thread: Thread = Thread.currentThread val thread: Thread = Thread.currentThread()
/** /**
* When this LogEvent was created according to System.currentTimeMillis * When this LogEvent was created according to System.currentTimeMillis
@ -969,7 +969,6 @@ object Logging {
/** /**
* LoggerInitializationException is thrown to indicate that there was a problem initializing a logger * LoggerInitializationException is thrown to indicate that there was a problem initializing a logger
* @param msg
*/ */
class LoggerInitializationException(msg: String) extends AkkaException(msg) class LoggerInitializationException(msg: String) extends AkkaException(msg)

View file

@ -605,11 +605,13 @@ private[akka] final class PromiseActorRef private (
case Stopped | _: StoppedWithPath => provider.deadLetters ! message case Stopped | _: StoppedWithPath => provider.deadLetters ! message
case _ => case _ =>
if (message == null) throw InvalidMessageException("Message is null") if (message == null) throw InvalidMessageException("Message is null")
if (!(result.tryComplete(message match { val promiseResult = message match {
case Status.Success(r) => Success(r) case Status.Success(r) => Success(r)
case Status.Failure(f) => Failure(f) case Status.Failure(f) => Failure(f)
case other => Success(other) case other => Success(other)
}))) provider.deadLetters ! message }
if (!result.tryComplete(promiseResult))
provider.deadLetters ! message
} }
override def sendSystemMessage(message: SystemMessage): Unit = message match { override def sendSystemMessage(message: SystemMessage): Unit = message match {
@ -639,7 +641,7 @@ private[akka] final class PromiseActorRef private (
def ensureCompleted(): Unit = { def ensureCompleted(): Unit = {
result.tryComplete(ActorStopResult) result.tryComplete(ActorStopResult)
val watchers = clearWatchers() val watchers = clearWatchers()
if (!watchers.isEmpty) { if (watchers.nonEmpty) {
watchers.foreach { watcher => watchers.foreach { watcher =>
// ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
watcher watcher

View file

@ -4,8 +4,8 @@
package akka.util package akka.util
import java.util.concurrent.locks.{ ReentrantLock } import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.atomic.{ AtomicBoolean } import java.util.concurrent.atomic.AtomicBoolean
final class ReentrantGuard extends ReentrantLock { final class ReentrantGuard extends ReentrantLock {

View file

@ -25,7 +25,7 @@ private[akka] object Reflect {
* executing in that stack frame. Implemented using * executing in that stack frame. Implemented using
* `sun.reflect.Reflection.getCallerClass` if available, None otherwise. * `sun.reflect.Reflection.getCallerClass` if available, None otherwise.
* *
* Hint: when comparing to Thread.currentThread.getStackTrace, add two levels. * Hint: when comparing to Thread.currentThread().getStackTrace, add two levels.
*/ */
val getCallerClass: Option[Int => Class[_]] = { val getCallerClass: Option[Int => Class[_]] = {
try { try {
@ -183,7 +183,7 @@ private[akka] object Reflect {
case c => c.getClassLoader case c => c.getClassLoader
} }
Option(Thread.currentThread.getContextClassLoader) Option(Thread.currentThread().getContextClassLoader)
.orElse(Reflect.getCallerClass.map(findCaller)) .orElse(Reflect.getCallerClass.map(findCaller))
.getOrElse(getClass.getClassLoader) .getOrElse(getClass.getClassLoader)
} }