views:

217

answers:

2

I am curious about how the following concepts typically execute inside a J2EE container, is one instance created per request, or does one instance serve all requests?

  • Servlets
  • Tags

I want to know this because lately i have been using a lot of StringBuffers in my custom tags, avoiding StringBuilder because it is not thread safe. Id like to know for sure how this stuff works so i can write better code

+1  A: 

Some app servers implement thread-pooling, which will execute a certain number of requests per thread, switching load between them as necessary. Simpler engines will spool a thread per request. However, if you never access your StringBuilder from multiple-threads at the same time, you should never have an issue with regards to thread-safety.

Chris Kaminski
+3  A: 

Both are correct. The container may reuse old instances for new requests and even create new instances if more requests are to be served.

Using StringBuilder should be safe as long as its usage does not cross the instances boundaries (by static usage, returning StringBuilders etc.). So if you're using it whithin a function/method to create your String-output, your're safe to do so.

Kosi2801