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)
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(
"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 = {
val contextStack = ActorCell.contextStack.get
if ((contextStack.isEmpty) || (contextStack.head eq null))
if (contextStack.isEmpty || (contextStack.head eq null))
throw ActorInitializationException(
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.")

View file

@ -382,7 +382,7 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin
private def addressStringLengthDiff(address: Address): Int = {
val r = root
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.
// Important: don't include calls to sendSystemMessage inside the synchronized since that can
// result in deadlock, see issue #26326
@ -948,7 +948,7 @@ private[akka] final class FunctionRef(
// AddressTerminatedTopic update not needed
block
case _ =>
def hasNonLocalAddress: Boolean = (watching.exists(isNonLocal)) || (watchedByOrEmpty.exists(isNonLocal))
def hasNonLocalAddress: Boolean = watching.exists(isNonLocal) || watchedByOrEmpty.exists(isNonLocal)
val had = hasNonLocalAddress
val result = block

View file

@ -499,7 +499,7 @@ private[akka] class LocalActorRefProvider private[akka] (
override def getSingleChild(name: String): InternalActorRef = name match {
case "temp" => tempContainer
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
throw t //Escalate to caller
} finally {
inProcessOfRegistration.countDown //Always notify listeners of the inProcess signal
inProcessOfRegistration.countDown() //Always notify listeners of the inProcess signal
}
case _ =>
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,
stopReason: Option[Reason] = stopReason,
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)
log.debug("setting " + (if (repeat) "repeating " else "") + "timer '" + name + "'/" + timeout + ": " + msg)
if (timers contains name) {
timers(name).cancel
timers(name).cancel()
}
val timer = Timer(name, msg, repeat, timerGen.next, this)(context)
timer.schedule(self, timeout)
@ -476,7 +476,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
if (debugEvent)
log.debug("canceling timer '" + name + "'")
if (timers contains name) {
timers(name).cancel
timers(name).cancel()
timers -= name
}
}
@ -686,7 +686,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
listeners.remove(actorRef)
case Deafen(actorRef) =>
listeners.remove(actorRef)
case value => {
case value =>
if (timeoutFuture.isDefined) {
timeoutFuture.get.cancel()
timeoutFuture = None
@ -694,7 +694,6 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging {
generation += 1
processMsg(value, sender())
}
}
private def processMsg(value: Any, source: AnyRef): Unit = {
val event = Event(value, currentState.stateData)

View file

@ -98,7 +98,7 @@ private[akka] class ArgsReflectConstructor(clz: Class[_ <: Actor], args: immutab
extends IndirectActorProducer {
private[this] val constructor = Reflect.findConstructor(clz, args)
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.concurrent.{ Await, ExecutionContext, Future, Promise }
import scala.concurrent.duration._
import scala.util.control.{ NonFatal }
import scala.util.control.NonFatal
import com.typesafe.config.Config
import akka.event.LoggingAdapter
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
try Thread.sleep(sleepMs)
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 =
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)
NotCancellable
} else if (stopped.get != null) {
throw new SchedulerException("cannot enqueue after timer shutdown")
throw SchedulerException("cannot enqueue after timer shutdown")
} else {
val delayNanos = delay.toNanos
checkMaxDelay(delayNanos)
@ -176,7 +176,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac
val task = new TaskHolder(r, ticks, ec)
queue.add(task)
if (stopped.get != null && task.cancel())
throw new SchedulerException("cannot enqueue after timer shutdown")
throw SchedulerException("cannot enqueue after timer shutdown")
task
}
@ -212,7 +212,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac
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
@ -237,7 +237,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac
checkQueue(time)
}
override final def run =
override final def run(): Unit =
try nextTick()
catch {
case t: Throwable =>
@ -334,8 +334,8 @@ object LightArrayRevolverScheduler {
executionContext.execute(other)
true
} catch {
case _: InterruptedException => { Thread.currentThread.interrupt(); false }
case NonFatal(e) => { executionContext.reportFailure(e); false }
case _: InterruptedException => Thread.currentThread().interrupt(); false
case NonFatal(e) => executionContext.reportFailure(e); false
}
}

View file

@ -272,7 +272,7 @@ private[akka] class UnstartedCell(
}
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 {
val cell = self.underlying
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 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
}
@ -179,7 +179,7 @@ private[akka] object ChildrenContainer {
override def getByName(name: String): Option[ChildStats] = c.get(name)
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
}

View file

@ -97,7 +97,7 @@ private[akka] trait DeathWatch { this: ActorCell =>
/** Call only if it was checked before that `watching contains ref` */
private def checkWatchingSame(ref: InternalActorRef, newMessage: Option[Any]): Unit = {
val previous = watching.get(ref).get
val previous = watching(ref)
if (previous != newMessage)
throw new IllegalStateException(
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 =
if (!watchedBy.isEmpty) {
if (watchedBy.nonEmpty) {
try {
// Don't need to send to parent parent since it receives a DWN by default
def sendTerminated(ifLocal: Boolean)(watcher: ActorRef): Unit =
@ -137,7 +137,7 @@ private[akka] trait DeathWatch { this: ActorCell =>
}
protected def unwatchWatchedActors(@unused actor: Actor): Unit =
if (!watching.isEmpty) {
if (watching.nonEmpty) {
maintainAddressTerminatedSubscription() {
try {
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)) {
def hasNonLocalAddress: Boolean = ((watching.keysIterator.exists(isNonLocal)) || (watchedBy.exists(isNonLocal)))
def hasNonLocalAddress: Boolean = watching.keysIterator.exists(isNonLocal) || watchedBy.exists(isNonLocal)
val had = hasNonLocalAddress
val result = block
val has = hasNonLocalAddress

View file

@ -120,7 +120,7 @@ private[akka] trait Dispatch { this: ActorCell =>
private def handleException: Catcher[Unit] = {
case e: InterruptedException =>
system.eventStream.publish(Error(e, self.path.toString, clazz(actor), "interrupted during message send"))
Thread.currentThread.interrupt()
Thread.currentThread().interrupt()
case NonFatal(e) =>
val message = e match {
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)
setReceiveTimeout(Duration.Undefined)
cancelReceiveTimeout
cancelReceiveTimeout()
// stop all children, which will turn childrenRefs into TerminatingChildrenContainer (if there are children)
children.foreach(stop)
@ -142,7 +142,7 @@ private[akka] trait FaultHandling { this: ActorCell =>
protected def terminate(): Unit = {
setReceiveTimeout(Duration.Undefined)
cancelReceiveTimeout
cancelReceiveTimeout()
// prevent Deadletter(Terminated) messages
unwatchWatchedActors(actor)
@ -180,8 +180,8 @@ private[akka] trait FaultHandling { this: ActorCell =>
suspendNonRecursive()
// suspend children
val skip: Set[ActorRef] = currentMessage match {
case Envelope(Failed(_, _, _), child) => { setFailed(child); Set(child) }
case _ => { setFailed(self); Set.empty }
case Envelope(Failed(_, _, _), child) => setFailed(child); Set(child)
case _ => setFailed(self); Set.empty
}
suspendChildren(exceptFor = skip ++ childrenNotToSuspend)
t match {

View file

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

View file

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

View file

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

View file

@ -709,7 +709,7 @@ object Logging {
* The thread that created this log event
*/
@transient
val thread: Thread = Thread.currentThread
val thread: Thread = Thread.currentThread()
/**
* 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
* @param 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 _ =>
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.Failure(f) => Failure(f)
case other => Success(other)
}))) provider.deadLetters ! message
}
if (!result.tryComplete(promiseResult))
provider.deadLetters ! message
}
override def sendSystemMessage(message: SystemMessage): Unit = message match {
@ -639,7 +641,7 @@ private[akka] final class PromiseActorRef private (
def ensureCompleted(): Unit = {
result.tryComplete(ActorStopResult)
val watchers = clearWatchers()
if (!watchers.isEmpty) {
if (watchers.nonEmpty) {
watchers.foreach { watcher =>
// ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅
watcher

View file

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

View file

@ -25,7 +25,7 @@ private[akka] object Reflect {
* executing in that stack frame. Implemented using
* `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[_]] = {
try {
@ -183,7 +183,7 @@ private[akka] object Reflect {
case c => c.getClassLoader
}
Option(Thread.currentThread.getContextClassLoader)
Option(Thread.currentThread().getContextClassLoader)
.orElse(Reflect.getCallerClass.map(findCaller))
.getOrElse(getClass.getClassLoader)
}