Mike Engelhart wrote:
> I have an application that uses a shared resource that is for all intensive
> purposes similar to a database connection. The only difference is that
> unlike a standard database connection I can't just create more connections
> in my connection pool like I can with my db connection pool (the reason is
> irrelevant but for those that question, setting up these connection objects
> entails a fee as well as about a week of time to get the service connected
> via a service call to the office).
>
> My question is whether or not calling Thread.sleep() within a servlet's
> doGet/doPost/service method until the connection is available is a
> safe/standard practice. This is a sample of what I'm thinking of doing:
>
> while ((myConn = getConnection()) == null)
> {
> Thread.sleep(250);
> }
>
This is not the way I would have approached it. Instead, I would've hidden any
waiting inside the getConnection() method itself. In fact, the connection pool I
use (home grown) has two versions of the getConnection call -- one that keeps
waiting "forever" for a connection to be available (once the configured maximum
number of connections have been created), and one that will return a timeout
exception after a specified number of milliseconds of waiting.
Inside this connection pool, I use the wait() and notify() mechanisms of Java,
rather than putting threads to sleep. There are examples of this in the threads
section of the Java Language Tutorial (http://java.sun.com/docs/books/tutorial) as
well as in books on multithread programming in Java.
>
> Is this thread safe?
This is thread safe as long as there are no problems inside the getConnection()
method itself.
>
> Any ideas of whether it will cause serious performance degradation?
>
Depends on your definition of serious, but consider the following scenario:
* I call getConnection() and it returns null,
so I start sleeping.
* One millisecond later, a connection is
released by some other thread.
* 249 milliseconds later (almost 1/4 second)
I find out about it and grab the connection.
The wait()/notify() approach avoids this problem by continuing in the waiting
thread immediately.
> Thanks for advice.
>
> Mike
>
Craig McClanahan
===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
FAQs on JSP can be found at:
http://java.sun.com/products/jsp/faq.html
http://www.esperanto.org.nz/jsp/jspfaq.html