5

We've run into a big discussion with colleagues about using threads in web-applications in Java.

Their point is that it is not recommended to use threading in Java web applications because they are not managed by the container. Generally, I'm OK with this, because threads may interfere with the container. But, what should one use instead of it if, for example, it is not a Java EE application but a simple servlet-app?

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
VasiliyL
  • 999
  • 8
  • 11

1 Answers1

10

Using threads in a webapp is not a problem per se. It just depends why and how you use them. In particular, if you have 1000 users, and you start one thread for each of these users, you'll bring the JVM to its knees.

But if threads are launched very raraely, for a specific, reduced set of users and use-cases, and if you use a thread pool to limit the number of such threads, you shouldn't have any problem. It's just important to understand what you're doing.

Also, make sure to not pass a HttpServletRequest or HttpServletResponse object to such a thread, because they aren't meant to be used by several concurrent threads, and they are not supposed to be used anymore once the request has been handled.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    Also, make sure any threads created for this case are *very* short-lived - otherwise you're in for a management hell, in that if you undeploy the web app, your threads may survive as zombies. Zombies, in this situation, are still very popular but well worth avoiding. – Joseph Ottinger Jul 02 '12 at 12:09
  • Thanks for your answer. In general you're proving my position that it is not a bad or discouraged practice to use them. It is just a matter of appropriate usage and careful coding which is true for every technology out there. – VasiliyL Jul 02 '12 at 12:25