ITPUB论坛 » Java企业开发 » 将connection存放在Threadlocal里和数据库连接池的区别
报名申请微软有影响力专家
2008-8-1 13:28 smartpig
将connection存放在Threadlocal里和数据库连接池的区别

我有几点不太明白的,望各位大侠指教下。
1、j2ee的应用中,有一个用户请求就会启动一个线程。而如果我们把connection放在Threadlocal里的话,那么我们的程序只需要一个connection连接数据库就行了,每个线程都是用的connection的一个副本,那为什么还有必要要数据库连接池呢?
2、在这种情况下一个副本里的connection执行了关闭操作,其他都没执行。那么想问一下真正与数据库连接的connection什么时候关闭呢?
3、显然上面的第一个问题是不成立的,但是希望哪位大侠帮我解释下。解释下什么时候是从数据库连接池里取connection而什么时候获得的是connection的一个Threadlocal副本?

2008-8-1 13:29 smartpig
怎么没人回呢?难道这个问题太傻了。可是我真的在这个问题上犯糊涂了,忘各位帮帮忙啊。

2008-8-1 14:26 Sky-Tiger
Well, yes you can use a connection in any thread, but understand that
the connection represents a single DBMS user doing a single series
of queries and/or updates, with one transaction in-force at any given
moment. As such, unless your threads are well coordinated to act
as a single DBMS user, it is much better for each thread to have it's own
connection

2008-8-1 14:31 Sky-Tiger
Use a thread local variable (where each thread has a separate value) when you want to carry a value along without explicitly passing it from method to method down the call stack, and when appropriate, remember to explicitly clear the value in a finally block to prevent memory leaks

2008-8-1 14:37 Sky-Tiger
线程池+连接池

每次线程出池的时候在threadlocal中放入通过连接池接口函数获取数据库连接;
在线程入池的时候,清理threadlocal中的数据库连接,将其放回连接池

2008-8-2 10:00 elathen
[quote]原帖由 [i]smartpig[/i] 于 2008-8-1 13:28 发表 [url=http://www.itpub.net/redirect.php?goto=findpost&pid=11134962&ptid=1031633][img]http://www.itpub.net/images/common/back.gif[/img][/url]
我有几点不太明白的,望各位大侠指教下。
1、j2ee的应用中,有一个用户请求就会启动一个线程。而如果我们把connection放在Threadlocal里的话,那么我们的程序只需要一个connection连接数据库就行了,每个线程都是用的connection的一个副本,那为什么还有必要要数据库连接池呢?
2、在这种情况下一个副本里的connection执行了关闭操作,其他都没执行。那么想问一下真正与数据库连接的connection什么时候关闭呢?
3、显然上面的第一个问题是不成立的,但是希望哪位大侠帮我解释下。解释下什么时候是从数据库连接池里取connection而什么时候获得的是connection的一个Threadlocal副本? [/quote]

数据库连接池是维护数connection的,每次和数据库交互的时候,都需要一个connection,这就是对应的DB中的一个session,至于你说的副本,不明白你的意思。

至于把connection 放在Threadlocal里面,只是每个connection和一个线程绑定。

2008-9-11 08:11 jack_xiong777
学到了

2008-9-12 08:40 greenflute
WY:

   what a mess of missunderstanding......

页: [1]


Powered by ITPUB论坛