Need thread safe MessageDigest in Java

前端 未结 3 2033
清酒与你
清酒与你 2020-12-23 20:45

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 stor

相关标签:
3条回答
  • 2020-12-23 21:41

    Create a newMessageDigest instance each time you need one.

    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 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).

    0 讨论(0)
  • 2020-12-23 21:43

    As an alternative, use DigestUtils, Apache Commons' thread-safe wrapper for MessageDigest.

    sha1() does what you need:

    byte[] bytes = sha1(key)

    0 讨论(0)
  • 2020-12-23 21:45

    You could use ImmutableMessageDigest from Caesar, an open source library I wrote.

    It essentially wraps a MessageDigest instance and clones it before every digest() or update() call.

    0 讨论(0)
提交回复
热议问题