Speed up BindingGeneratorUtil.makeSerializable() 50/29350/3
authorRobert Varga <rovarga@cisco.com>
Tue, 3 Nov 2015 21:35:36 +0000 (22:35 +0100)
committerGerrit Code Review <gerrit@opendaylight.org>
Mon, 16 Nov 2015 12:03:02 +0000 (12:03 +0000)
Instead of performing lookup on every call, use a thread-local instance
which can be reused.

Change-Id: I45e7170bcfe06bb76f87d723a703f9849e9da4a3
Signed-off-by: Robert Varga <rovarga@cisco.com>
binding/mdsal-binding-generator-util/src/main/java/org/opendaylight/yangtools/binding/generator/util/BindingGeneratorUtil.java

index 3257d10afdaf0343d6511ab47db5a62403541cb2..41f30ca257ec453c19dbaa54f6f524e85e50a80d 100644 (file)
@@ -401,11 +401,20 @@ public final class BindingGeneratorUtil {
         }
     }
 
-    public static long computeDefaultSUID(final GeneratedTypeBuilderBase<?> to) {
-        try {
-            ByteArrayOutputStream bout = new ByteArrayOutputStream();
-            DataOutputStream dout = new DataOutputStream(bout);
+    private static final ThreadLocal<MessageDigest> SHA1_MD = new ThreadLocal<MessageDigest>() {
+        @Override
+        protected MessageDigest initialValue() {
+            try {
+                return MessageDigest.getInstance("SHA");
+            } catch (NoSuchAlgorithmException e) {
+                throw new IllegalStateException("Failed to get a SHA digest provider", e);
+            }
+        }
+    };
 
+    public static long computeDefaultSUID(final GeneratedTypeBuilderBase<?> to) {
+        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
+        try (final DataOutputStream dout = new DataOutputStream(bout)) {
             dout.writeUTF(to.getName());
             dout.writeInt(to.isAbstract() ? 3 : 7);
 
@@ -425,21 +434,16 @@ public final class BindingGeneratorUtil {
             }
 
             dout.flush();
+        } catch (IOException e) {
+            throw new IllegalStateException("Failed to hash object " + to, e);
+        }
 
-            try {
-                MessageDigest md = MessageDigest.getInstance("SHA");
-                byte[] hashBytes = md.digest(bout.toByteArray());
-                long hash = 0;
-                for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
-                    hash = (hash << 8) | (hashBytes[i] & 0xFF);
-                }
-                return hash;
-            } catch (NoSuchAlgorithmException ex) {
-                throw new SecurityException(ex.getMessage());
-            }
-        } catch (IOException ex) {
-            throw new InternalError();
+        final byte[] hashBytes = SHA1_MD.get().digest(bout.toByteArray());
+        long hash = 0;
+        for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
+            hash = (hash << 8) | (hashBytes[i] & 0xFF);
         }
+        return hash;
     }
 
     public static Restrictions getRestrictions(final TypeDefinition<?> type) {