Avoid declaring a field type as MessageDigest

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: java-best-practices/avoid-message-digest-field

Language: Java

Severity: Notice

Category: Best Practices

Description

When you designate a MessageDigest instance as a class member, you enable direct access for multiple threads in your program. It is important to exercise caution when sharing instances among threads without proper synchronization.

Instead of sharing a single MessageDigest instance, consider generating new instances when necessary and using them locally within the specific context where they are needed. This practice offers two benefits. First, it guarantees that each thread operates on its own instance, thereby minimizing the possibility of interference between threads. Second, it sidesteps the intricacies of managing synchronized access to a shared instance.

Non-Compliant Code Examples

public class Foo {
    private final MessageDigest sharedMd; // should avoid this
    
    public Foo() throws Exception {
        sharedMd = MessageDigest.getInstance("SHA-256");
    }
    
    public byte[] bar(byte[] data) {
        // Incorrect outcomes could arise from sharing a 
        // MessageDigest without synchronized access.
        sharedMd.reset();
        sharedMd.update(data);
        return sharedMd.digest();
    }
}

Compliant Code Examples

public class Foo {
    public byte[] bar(byte[] data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data);
        return md.digest();
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: rtrieu/product-analytics-ui-changes