ExecutorService中的持久变量(Java) [英] Persistent Variables in ExecutorService (Java)

查看:541
本文介绍了ExecutorService中的持久变量(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个4个工作线程池来处理一些文件。在测试中有约200个。

I've created a pool of 4 worker threads to process some files. In the test there's about 200 of them. The thread pool version is already about 3 times faster than doing it sequentially but there is room for improvement.

最大的瓶颈(忽略磁盘I / O)是我需要来实例化一个新的MessageDigest对象。在单线程版本中我只有1.在这个版本中我有200。

The biggest bottleneck (ignoring disk I/O) is that I need to instantiate a new MessageDigest object. In the single threaded version I just had 1. In this version I have 200.

我想知道的是,可能有一个变量局部的线程工作池?这样(假设没有线程死亡)只有四个MessageDigest对象的实例,而不是200 ...

What I was wondering was, is it possible to have a variable local to the thread in the work pool? That way (assuming no threads die) there would only be four instances of the MessageDigest object rather than 200...

每个任务需要摘要,所以我不确定如果有更好的方法做它...

Each task requires the digest so I'm not sure if there's a better way to do it...

我试图使用ThreadLocal对象,我应该在哪里创建它?如果我在任务本身创建它,我猜它在任务完成时上下文。每次创建一个新实例。我的代码是:

I tried to use a ThreadLocal object but where should I create it? If I create it in the task itself, I guess it goes out of context when the task is completed. Each time a new instance is created. The code I have is:

    ThreadLocal<GenerateSHA1> tl = new ThreadLocal<GenerateSHA1>();

    hashMaker = tl.get();
    if(hashMaker == null){
        hashMaker = new GenerateSHA1();
        tl.set(hashMaker);
    }

这是从任务的构造函数内部完成的。

This is done from inside the constructor of the task.

UPDATE

好吧,使它静态的工作,因为对象不会丢失 - 但现在突出了一个不同的问题。工作任务在主线程中创建,然后使用invokveAll()添加到ExecutorService。

Okay making it static sort of works in that the object is not lost - but it's now highlighted a different issue. The work "tasks" are create in the Main thread and then added to the the ExecutorService with invokveAll().

有关如何解决这个问题的任何建议吗?

Any ideas on how to work around this?

推荐答案

ThreadLocal ,并覆盖 initialValue()方法。

private static class ThreadLocalGenerateSHA1 extends
  ThreadLocal<GenerateSHA1> {

  @Override
  protected GenerateSHA1 initialValue() {
    return new GenerateSHA1();
  }

}

private static final ThreadLocalGenerateSHA1 generateSHA1 = new ThreadLocalGenerateSHA1();

...

在任务上,只需调用 get() generateSHA1的方法。您不需要调用 set()

On the tasks, simply call the get() method of generateSHA1. You do not need to call set().

这篇关于ExecutorService中的持久变量(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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