Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am fairly new to Java and my experience is limited to Web Based Applications running on a Web Container (Jboss in my case).

Am I correct in saying that for Web Applications the web container takes care of multi-threading? If so, can I introduce new treads in a Web Based applications? Is there any advantage in doing so and in what scenario one would need to do that?

share|improve this question
Till EE6 Thou Shall Not Use Threads; EE7 introduces Concurrency Utilities. – Martin Schröder Jun 12 at 18:20
up vote 8 down vote accepted

Am I correct in saying that for Web Applications the web container takes care of multi-threading?

Most webservers (Java and otherwise, including JBoss) follow a "one thread per request" model, i.e. each HTTP request is fully processed by exactly one thread. This thread will often spend most of the time waiting for things like DB requests. The web container will create new threads as necessary.

Some servers (in the Java ecosystem primarily Netty) do asynchronous request handling, either with a "one thread does everything" model, or something more complex. The basic idea there is that having lots of waiting threads wastes resources, so working asynchronously can be more efficient.

If so, can I introduce new treads in a Web Based applications?

It's possible, but should be done very carefully, since errors (like memory leaks or missing synchronization) can cause bugs that are very hard to reproduce, or bring down the whole server.

Is there any advantage in doing so and in what scenario one would need to do that?

Well, the advantage is that you can do stuff in parallel. Using threads to improve pure computational speed is something you should not do on a webserver, as it would slow down the handling of other requests. That kind of thing should be done on a separate server, probably using some sort of job queue.

A legitimate scenario for multithreading in the context of handling an HTTP request might be if you need to access other network resources, e.g. call several different web services. If you do it in a single thrad, you have to wait for each call to finish in turn. But if you use multiple threads, the total waiting time is only the delay of the single slowest call.

share|improve this answer
Makes sense. Is ExecutorService Interface the best way to go about creating new threads in a web application? – kapricanon Jun 12 at 13:30
@kapricanon: yes, unless you have some specific requirements it can't handle, or your web server already has something similar. – Michael Borgwardt Jun 12 at 13:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.