本文介绍了需要Java中的线程安全MessageDigest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在性能关键环境中使用MessageDigest从多个线程中散列多个键。我开始知道MessageDigest不是线程安全的,因为它将状态存储在它的对象中。什么是实现密钥线程安全散列的最佳方法?

I need to hash multiple keys from multiple threads using MessageDigest in a performance critical environment. I came to know that MessageDigest is not thread safe as it stores its state in it's object. What can be the best possible way to achieve thread safe hashing of keys?

用例:

MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");

//somewhere later, just need to hash a key, nothing else
messageDigest.update(key);
byte[] bytes = messageDigest.digest(); 

具体来说:


  1. ThreadLocal会保证有效吗?它会有性能
    罚款吗?

  2. getInstance返回的对象是否不同,
    是否互不干扰?文档说'new'
    对象,但我不确定它是否只是(共享)
    共享具体类的包装器?

  3. 如果getInstance()返回真正的新对象,那么每次需要
    计算哈希时,建议创建一个新实例
    ?在性能损失方面 -
    的成本是多少?

我的用例非常简单 - 只需散列一个简单的密钥。我不能使用同步。

My use case is very simple - just hash a simple key. I cannot afford to use synchronization.

谢谢,

推荐答案

创建每次需要一个新的 MessageDigest 实例。

Create a newMessageDigest instance each time you need one.

返回的所有实例getInstance()是不同的。他们需要,因为他们维护单独的摘要(如果这对你不够,指向源的链接。)

All of the instances returned from getInstance() are distinct. They need to be, as they maintain separate digests (and if that's not enough for you, here's a link to the source).

ThreadLocal 可以在与线程池一起使用时提供性能优势,以维护昂贵的构造对象。 MessageDigest 构建起来并不是特别昂贵(再次查看源代码)。

ThreadLocal can provide a performance benefit when used with a threadpool, to maintain expensive-to-construct objects. MessageDigest isn't particularly expensive to construct (again, look at the source).

这篇关于需要Java中的线程安全MessageDigest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:36