Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.sleep inside Scala actors

Is it correct to use Thread.sleep(5000); inside an actor? Does it actualy make an actor sleep for 5 seconds? Is there a simple alternative to make an actor sleep for some seconds?

like image 662
As As Avatar asked Sep 11 '14 14:09

As As


People also ask

How do you create a thread in Scala?

In Scala, threads are created in two ways: First, is Extending the Runnable Interface, and the second is Extending the Thread class. We create a class that extends the Runnable interface and override the run () method. Thread 1 is running. Thread 2 is running. Thread 3 is running. Thread 4 is running. Thread 5 is running.

How does the sleep method work in Scala?

Then, we will see how the Sleep method works in Scala. Threads are lightweight sub-processes that take less space and run faster. In a multi-threaded environment, many threads run concurrently, each performing a different task. This leads to better CPU utilization and resources, and in turn, we get better throughput.

What is a multi-threaded environment in Scala?

In a multi-threaded environment, many threads run concurrently, each performing a different task. This leads to better CPU utilization and resources, and in turn, we get better throughput. In Scala, threads are created in two ways: First, is Extending the Runnable Interface, and the second is Extending the Thread class.

What is the API of Scala actors?

This guide describes the API of the scala.actors package of Scala 2.8/2.9. The organization follows groups of types that logically belong together. The trait hierarchy is taken into account to structure the individual sections.


1 Answers

Anything that blocks a thread is not advised within Akka. If the Actor is configured with a a shared thread pool (default behavior) then using Thread.sleep will withhold a thread from that pool that could be doing work for other Actors.

If one really must block, then an actor may be configured to have its own thread. This can be done by configuring a custom dispatcher for the actor to use, the full details are here.

The recognized alternative to blocking is to schedule a callback to the actor via a timer, for example send a message after 5 seconds..

akkaSystem.scheduler.scheduleOnce(5 seconds, actor, "msgFoo")

The Akka scheduler is documented here: http://doc.akka.io/docs/akka/2.3.6/scala/scheduler.html

like image 178
Chris K Avatar answered Sep 19 '22 15:09

Chris K