欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

加密工具类导致内存溢出

程序员文章站 2022-07-13 13:16:25
...
    /**
     * 私钥解密
     * @desc
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data,
                                             RSAPrivateKey privateKey) throws Exception {
        //每次都是new一个对象
        Cipher cipher = Cipher.getInstance(TRANSFORMATION,new BouncyCastleProvider());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

 new BouncyCastleProvider() 是静态方法中的, new一个多一个,GC不回收, 慢慢就宕机。

改成单例模式

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class SingletonBouncyCastleProvider {
	
	
	public SingletonBouncyCastleProvider() {}
	
	private static BouncyCastleProvider singleton=null;
	
	public static BouncyCastleProvider getInstance() {
		if(singleton==null) {
			synchronized(SingletonBouncyCastleProvider.class){
				if(singleton==null) {
					return new BouncyCastleProvider();
				}
			}
		}
		return singleton;
	}

}

Cipher cipher = Cipher.getInstance(TRANSFORMATION,SingletonBouncyCastleProvider.getInstance());

 

相关标签: 内存溢出