0

在一次工作会议上。听说Thread Local绝对是一种反模式,因为新的应用服务器使用了新的线程技术,称为新IO。实际上,他们告诉我,ThreadLocal的问题是一个完整的线程必须等待数据库查询返回响应,这绝对是对资源(内存和 CPU)的浪费。新开发的线程策略使用线程池,因此当不再需要线程时,它将返回池。我听说这项新技术是在新的 AS 中实现的,例如我们 Jboss、Websphere ......(我没有把握)。例如,我可以在本地使用它与 Apache tomcat 吗?(如果可能有关于该事实的文档)

4

4 回答 4

6

ThreadLocal是你故事中的配角。您听说过的是异步请求处理,其中包括 NIO 库的帮助。

在这种编程范式中,您不会得到像这样的简单方法

Response processRequest(Request req)

相反,你得到

void requestReceived(Request req, Response resp)

在这个方法中,你通常会通过准备后端请求并调用它的方法来开始处理,这看起来像

execute(Query q, ResultCallback cb)

并且框架将调用您ResultCallbackresultReady(Result res)包含查询结果的方法。

这里的重点是该方法requestReceived立即返回,并且不会在后端子系统处理后端请求时占用线程。

BTW another name for this style of programming is continuation-passing style or CPS. It is because when you call a function, you don't wait for its return value, but rather pass a callback into it which will be called with the function's result, and which implements the continuation of the total request processing.

How ThreadLocal fits into this

If you have followed what I have said above, it should already be clear to you that in this style of request processing, ThreadLocals are a useless concept because the request processing freely jumps from thread to thread, and in a way which is completely outside of your control.

于 2013-07-24T11:18:54.503 回答
1

ThreadLocal 基本上与数据库或 ThreadPools/ExecutorServices 无关。ThreadLocal 只是意味着存储在其中的值对于 Thread 如何设置它是可见的。这不会导致任何阻塞。你必须混淆那里的一些东西。

  • ThreadLocal:为每个线程存储变量。
  • “新 IO”:它们很可能是指java.nio 包。它关于无阻塞地读取/写入数据。
  • Threadpools/Executorservice:可以向其中提交 Runnables 的一组线程。您可以在任何 Java 应用程序中使用ExecutorServices,因为它们是标准库的一部分。
  • 为了访问数据库,您通常使用像C3P0这样的专用系统,它管理线程和数据库连接
于 2013-07-24T11:17:31.680 回答
0

I think that i misunderstand the subject. Well,i will explain in detail what i have heard. When using ThreadLocal.If we have for example a query to DataBase or JMS call .The thread must be alive for the response to return (suppose that takes 15 minute for example).The thread will be in a waiting situation waiting for Db to return response.so it's a waste for CPU as well as memory. New Thread management technology uses a pool of threads.In fact during the waiting time.The thread will be used to server another client. That's what i have heard. To Marko Topolnik:What you have exposed is asynchronous calls and it does nothing to do with Threads.

于 2013-07-24T11:26:32.503 回答
0

ThreadLocals, thread pools, and new IO can cooperate quite well. All you need is to define thread factory when creating a threadpool so that each new thread would get correct threadlocal value at the moment of creation. This value, for example, can keep a reference to java.nio.channels.Selector singleton. Another thread local variable can hold reference to the thread pool itself, so submitting new tasks to the thread pool can be simplified.

Asynchronous framework https://github.com/rfqu/df4j uses thread locals intensively this way.

于 2013-07-24T20:30:17.953 回答