File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

jdbc and Threads...Theory

 
Hanna Habashy
Ranch Hand
Posts: 532
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all:
According to my understanding of Threads and Connection pool, I have this theory, which I don't know if it is correct or not.
Assuming a single proccessor machine, only one thread can be excuted at a time. Threads alternate, but only one thread can be excuted at one time. For simplicity, consider a web application with one servlet. Inside this servlet there is a single method that can access the database.
Here is the quistion:
1- will it be more effecient to creat a single connection object to the poole, in the initilizaion proccess of the application, and leave it open, so all thread can access it sequentially?
2- or, it is more effecient to create a new connection and statement objects inside the method, and then close the connection before the method return?
From my understanding of how Threads work, case one shuold eleminate unnecesarry creation of objects, every time a thread ask to access this method, and overall should be better performace.
I did a test on both cases, and I was surprised that case number 2 won. The time needed to create about 5000 connection in 5 threads was much less than in case number 1.
any help in uderstanding what is going on or ideas is appreciated.
 
James Carman
Ranch Hand
Posts: 580
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's just one problem with your theory. It is true that only one thread can REALLY be running at any given time on a single-processor machine. However, the threads are not allowed to run all the way to completion when they DO get the processor. They are each given a chunk of time to do some work, and you do not have any control over WHEN your thread will lose the processor and another will take over. Consider the following scenario where two different threads share the same Connection object (and thus the same transaction)...
Thread 1 debits a bank account.
Thread 2 rolls back the current transaction.
Thread 1 credits another bank account.
Thread 1 commits the current transaction.
What Thread 1 wanted to do was a transfer from one account to another within one transaction. What actually happened, since Thread 2 rolled back the transaction without Thread 1 knowing it, was simply a credit to a bank account.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic