Java执行器和每线程(不是每个工作单元)对象? [英] Java Executors and per-thread (not per-work unit) objects?

查看:255
本文介绍了Java执行器和每线程(不是每个工作单元)对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务将受益于线程池设计模式(许多小任务要并行执行)。我最初从头开始实现了一个天真的线程池,其中n个Runnables都从相同的 ConcurrentLinkedQueue 中拉出工作单元,直到队列为空,然后终止。然后我决定嘿,让我们尝试Java中的Executor,因为这可能比我天真设计的系统更好地测试和更可靠。问题:在我的实现中,每个线程持续到队列为空,使用while (!queue.isEmpty()),并获得了自己的非线程安全实例对象,我们称之为 SlowObject foo ,这构建起来非常耗时。试图传递进入 Executor 的池的所有 Runnable ,时间效率低的对象的实例失败,因为它不是线程安全的。为每个 Runnable 创建 SlowObject 的新实例是不合需要的,因为它们的构造成本很高。

I have a task that would benefit from the Thread Pool design pattern (many small tasks to be performed in parallel). I initially implemented a naive thread pool from scratch, with n Runnables all pulling work units from the same ConcurrentLinkedQueue until the queue is empty, then terminating. I then decided "hey, let's try the Executor in Java, because that is probably better-tested and more reliable than my naively designed system." Problem: in my implementation, each thread persisted until the queue was empty, using a while (!queue.isEmpty()), and got its own instance of a non-threadsafe object, let's call it SlowObject foo, that is time-consuming to construct. Trying to pass all Runnables that go into the Executor's pool an instance of the time-inefficient object fails because it is not thread-safe. Creating a new instance of SlowObject for each Runnable is undesirable because they are costly to construct.

有没有办法说我们使用了多少线程?让我们为每个线程创建一个 SlowObject ,然后让Runnables检测我们所在的线程并查找要使用的正确对象?这听起来很脆弱且容易出错 - 但不确定我应该考虑哪种设计模式。

Is there a way to say "how many threads are we using? Let's create one SlowObject for each thread, and then let the Runnables detect what thread we're on and look up the correct object to use?" This sounds brittle and failure-prone -- not sure what design pattern I should be looking at instead, though.

推荐答案

Java提供 ThreadLocal 变量的概念。 >
您可以在 Runnable <中使用它/ a>像这样。

Java provides the concept of a ThreadLocal variable.
You can use it within your Runnable like this.

 public class MyJob implements Runnable {
     private static final ThreadLocal < SlowObject > threadLocal = 
       new ThreadLocal < SlowObject > () {
         @Override protected SlowObject initialValue() {
           // construct and return your SlowObject 
         }
       };

     public void run() {
       // work with threadLocal.get()
     }
   }

因此,对于运行Runnable的每个线程,只创建一个SlowObject类的实例。

Thereby for each thread running your Runnable only a single instance of your class SlowObject is created.

这篇关于Java执行器和每线程(不是每个工作单元)对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆