我的问题是我正在解密/加密来自不同线程的一些随机值字符串集,但经过多次迭代后,内存迅速增加。
我的观察是内存增加是因为每次加密/解密都会产生新的字符串,因此内存会增加。
需要注意的另一点是,我的解密/加密字符串将具有如此多的相同值,因为相同的字符串集(某些字符串可能是新的(是从许多线程加密/解密的,但由于在每个加密/解密中,密码返回字节数组并再次构成字符串我必须使用"new String(("函数,这可能会或将迅速增加内存。
这是我加密/解密字符串的代码
public static String encrypt(String key, String value) throws GeneralSecurityException
{
byte[] raw = key.getBytes();
if (raw.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
byte[] cipherBytes= cipher.doFinal(value.getBytes());
byte[] encoded = org.apache.commons.codec.binary.Base64.encodeBase64(cipherBytes);
return new String(encoded);
}
public static String decrypt(String key, String encrypted) throws GeneralSecurityException
{
byte[] raw = key.getBytes();
if (raw.length != 16) {
throw new IllegalArgumentException("Invalid key size.");
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
byte[] byteDecodedText = org.apache.commons.codec.binary.Base64.decodeBase64(encrypted.getBytes()) ;
byte[] original = cipher.doFinal(byteDecodedText);
return new String(original);
}
字符串实习方法可能是要走的路。它返回字符串的规范表示形式,因此对于相同的字符串,您将只有一个实例。因此,当您返回字符串时,请尝试执行以下操作:
new String(byteDecryptedText).intern();
超出范围后,将收集使用 new 创建的字符串的实例。将返回内部对象。
确实,每次迭代都会产生新的字符串,但我认为这不会很快增加内存,因为字符串所需的内存以字节为单位。
根据字符串内存使用情况,您可以计算加密或解密的字符串的大小。这可以让您了解内存增加是否是由于每次形成新字符串。