To Pool or not to Pool java crypto service providers

后端 未结 2 1352
一个人的身影
一个人的身影 2021-02-01 09:58

Solution

  • MessageDigest => create new instances as often as needed
  • KeyFactory => use a single shared instance
  • SecureRandom => use a StackObject
2条回答
  •  梦毁少年i
    2021-02-01 10:11

    If you give 100 threads access to a shared MessageDigest and get them to calculate 1,000,000 hashes each then on my machine the first thread finishes in 70,160ms and the last finishes in 98,748ms.

    If the threads create a new instance of MessageDigest each time, then the first thread finishes in 43,392ms and the last 58,691ms.

    Edit:
    In fact with this example, with only two threads the example creating new instances runs quicker.

    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class Share {
    
      final byte[] bytes = new byte[100];
      final MessageDigest sharedDigest;
      final ExecutorService pool;
      int threads = 100;
    
      Share() throws NoSuchAlgorithmException {
        sharedDigest = MessageDigest.getInstance("MD5");
        pool = Executors.newFixedThreadPool(threads);
      }
    
      void go() {
    
        for (int i=0; i

提交回复
热议问题