简体   繁体   中英

Scala actors, futures and system calls resulting in Thread leaks

I am running a complex software with different actors (scala actors). Some of them have some executions that uses scala futures to avoid locking and keep processing new received messages (simplified code):

  def act {
    while (true) {
      receive {
        case (code: String) =>
          val codeMatch = future { match_code(code) }
          for (c <- codeMatch)
            yield callback(code)(JSON.parseJSON(c))
      }
    }
  }

  def match_code(code: String) {
     val result = s"my_script.sh $code" !!
  }

I noticed looking at jvisualvm and Eclipse Debugger that the number of active threads keeps increasing when this system is running. I am afraid I am having some kind of Thread leak, but I can't detect where is the problem.

Here are some screenshots of both finished and live threads (I hided some live threads that are not related to this problem)

Finished Threads 成品螺纹

Living threads 活动线程

Edit 1: In the above graphs example, I run the system with only 3 actors of different classes: Actor1 sends messages to Actor2 that sends message to Actor3

You are using receive so each actor will use its own thread, and you don't at least in this example provide any way for actors to terminate. So you would expect to have one new thread per actor that was ever started. If that is what you see, then all is working as expected. If you want to have actors cease running, you will have to let them eventually fall out of the while loop or call sys.exit on them or somesuch.

(Also, old-style Scala actors are deprecated in favor of Akka actors in 2.11.)

You also don't (in the code above) have any indication whether the future actually completed. If the futures don't finish, they'll keep tying up threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM