java.lang.OutOfMemoryError: unable to create new native thread

I have an actor that is created as:

context.actorOf(MyActor.props)

Inside MyActor, some remote service calls are made to fetch data as part of receive method.

Additionally a thread is spawn when actor is created to perform some additional work:

val myThread = new Thread() {
   ......
   ......
    override def run(): Unit = {
          running = true
          while (running) {
            performTask(....)
            Thread.sleep(10000)
          }
        }
}
myThread .start()
....

Is this way of doing things inside an actor a good practise?

Problem I am facing is that soemtimes I see error:

java.lang.OutOfMemoryError: unable to create new native thread
	at java.lang.Thread.start0(Native Method)

Any lead is welcome.

Hi @mghildiy1,

No, that’s not a good practice.

Starting threads are very costly.
Both Java and Scala offers APIs to create thread pools. Instead of spawning threads yourself, you should use CompletionStage (java) or a Future (scala).

I see you are using Scala, so maybe the best is to get familiar with Futures and ExecutionContext in Scala first.

Once you get a good understanding of how you should use them, you should look at how to use Futures inside Actors. Here is a good place to start: Interaction Patterns • Akka Documentation
But first make sure you get familiar with Futures in Scala.

Regards,

Renato

Think actor as a fiber, so there is no need to create the Thread. you need a dedicated thread pool to manage your blocking or use VirtualThread.