ファイル出力ストリームで圧縮、暗号化、およびチェックサムを行うコードがあります。以下はコードです-
private void start() {
OutputStream os = null;
try {
os = new FileOutputStream("/some/file");
os = wrapAllRequiredTransforms(os);
//Write to os
} finally {
os.close();
}
}
private wrapAllRequiredTransforms(OutputStream os) {
if(checkSumRequired) {
os = wrapOStreamWithCheckSum(os);
}
if(encryptionRequired) {
os = wrapOStreamWithCipher(os);
}
if(compressRequired) {
os = wrapOStreamWithCompress(os);
}
}
private OutputStream wrapOStreamWithCheckSum(OutputStream os) throws Exception {
os = new DigestOutputStream(os, MessageDigest.getInstance("MD5"));
return os;
}
private OutputStream wrapOStreamWithCipher(OutputStream os) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(//SomeKey, encryptionAlgorithm);
Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return new CipherOutputStream(os, cipher);
}
private OutputStream wrapOStreamWithCompress(OutputStream os) throws Exception {
return new GZIPOutputStream(os);
}
ここでわかるように、暗号化、圧縮などのために「os」オブジェクトをラップしてから、wrapOStreamWithCheckSum、wrapOStreamWithCipher、および wrapOStreamWithCompress メソッドのそれぞれの内部で、別のオブジェクト (new を使用して作成) で「os」変数を再割り当てしています。これが万が一メモリリークにつながるのではないかと思っていましたか?作成された古い「os」オブジェクトは実際にどうなるのでしょうか? 言い換えると、「new」を使用して作成された 4 つのオブジェクトがありますが、同じ「os」変数に再割り当てされています。新しいオブジェクトの作成/機能自体が古いオブジェクトに内部的に依存しているため、理解するのが難しいと感じています。