Sobes.tech
Junior — Senior

Analysis of thread safety of the entity creation method in DataService

livecode

Task condition

It is necessary to review the code of the DataService class responsible for working with Data objects. The create method can be called simultaneously from different threads, so its implementation must be safe for multi-threaded access. Meanwhile, AccessService and DataRepository already guarantee correct operation in a multi-threaded environment. It is necessary to suggest options for improving the implementation and indicate what the current problem is, if any.

public class DataService {
    private AccessService accessSrv;
    private DataRepository repo;
    private MessageDigest mdDigest = createDigest();

    public DataService(AccessService accessSrv, DataRepository repo) {
        this.accessSrv = accessSrv;
        this.repo = repo;
    }

    public Data get(String uid) {
        accessSrv.checkRead();
        return repo.get(uid);
    }

    public void create(String name) {
        accessSrv.checkWrite();
        mdDigest = createDigest();
        repo.save(new Data(
            HexFormat.of().formatHex(mdDigest.digest(name.getBytes())),
            name
        ));
    }

    public static MessageDigest createDigest() {
        try {
            return MessageDigest.getInstance("md5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException();
        }
    }

    public record Data(
        String uid,
        String name
    ) {}

    public interface DataRepository {
        void save(Data data);
        Data get(String uid);
    }

    public interface AccessService {
        void checkRead();
        void checkWrite();
    }
}