< prev index next >

src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Key.java

Print this page

        

@@ -43,10 +43,11 @@
 import sun.security.internal.interfaces.TlsMasterSecret;
 
 import sun.security.pkcs11.wrapper.*;
 import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
 
+import sun.security.util.Debug;
 import sun.security.util.DerValue;
 import sun.security.util.Length;
 import sun.security.util.ECUtil;
 
 /**

@@ -1108,14 +1109,31 @@
     static ReferenceQueue<P11Key> referenceQueue() {
         return refQueue;
     }
 
     private static void drainRefQueueBounded() {
+        Session session = null;
+        Token token = null;
         while (true) {
             SessionKeyRef next = (SessionKeyRef) refQueue.poll();
-            if (next == null) break;
-            next.dispose();
+            if (next == null) {
+                break;
+            }
+            try {
+                // If this key's token is the same as the previous key, the
+                // same session can be used for C_DestroyObject.
+                if (next.session.token != token) {
+                    // If we have a previous token and session, release the session
+                    if (token != null && session != null)
+                        token.releaseSession(session);
+                    token = next.session.token;
+                    session = token.getOpSession();
+                }
+                next.dispose(session);
+            } catch (PKCS11Exception e) {
+                // ignore
+            }
         }
     }
 
     // handle to the native key
     private long keyID;

@@ -1125,29 +1143,28 @@
         super(key, refQueue);
         this.keyID = keyID;
         this.session = session;
         this.session.addObject();
         refList.add(this);
-        // TBD: run at some interval and not every time?
         drainRefQueueBounded();
     }
 
-    private void dispose() {
-        refList.remove(this);
-        if (session.token.isValid()) {
-            Session newSession = null;
+    private void dispose(Session s) {
             try {
-                newSession = session.token.getOpSession();
-                session.token.p11.C_DestroyObject(newSession.id(), keyID);
+            session.token.p11.C_DestroyObject(s.id(), keyID);
             } catch (PKCS11Exception e) {
                 // ignore
             } finally {
-                this.clear();
-                session.token.releaseSession(newSession);
-                session.removeObject();
+            dispose();
             }
+
         }
+
+    private void dispose() {
+        refList.remove(this);
+        this.clear();
+        session.removeObject();
     }
 
     public int compareTo(SessionKeyRef other) {
         if (this.keyID == other.keyID) {
             return 0;
< prev index next >