• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why doesn't this multithreaded code terminate properly?  RSS feed

 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm really sorry if this is not the right way to ask this question, but I was horsing around with lamda functions and what not in java 1.8 and I found out that my simple program doesn't terminate. It prints all the expected results right to the last line of main, but I have to hit ctrl+c for the program to properly terminate. I don't see where I have any open threads still running. Here's the code: Output

Sequential manipulation completed in 511 milliseconds.
Parallel manipulation completed in 455 milliseconds.
^c
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that your 'sequential' and 'parallel' tests are running at the same time; that's not a very good way to compare how long it takes to run them. I'd run them one after the other. Why did you implement it this way, with an executor etc.?

In your current code, the executor is not being shut down unless you press Ctrl+C. (Note that when the main method ends, that isn't the same thing as the JVM shutting down - the shutdown hook is not going to be called automatically when the main method returns. You have to add a call to executor.shutdown() at the end of your main method.

I'd make it simpler and remove the whole executor business:
 
Ra Carter
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi thank you very much for your help. Honestly I created the executor functions just to mess around with lamdas, but why wouldn't the executor shut down if there are no more open threads running in it?

edit: I totally agree things would be simpler with that stuff removed, but I was kind of doing things the hard way just to learn.
 
Rancher
Posts: 2762
32
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The executor threads are always alive but idle when it's not running any tasks until you tell it to shutdown. That's the whole point of having an executor. Creating threads is costly. If you are going to be continuously running tasks in the background, it's better to keep a pool of threads alive than create a new one for every task.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!