У меня есть класс, который я должен сделать потокобезопасным, без применения конкаренси коллекций. И в этом классе есть целый ряд методов, я использую один объект-монитор, на все методы, но я не уверен достаточно ли этого или надо на каждый метод свой? Или на оборот он и должен быть один, что-бы пропускать только один поток?
public class UserStorage implements Storage {
private Map<Integer, Account> accounts;
private final Object monitor;
UserStorage() {
this.accounts = new HashMap<>();
this.monitor = new Object();
}
@Override
public boolean addAccount(final Account account) {
synchronized (monitor) {
Account a = this.accounts.get(account.getId());
if (a != null) {
return false;
}
this.accounts.put(account.getId(), account);
return true;
}
}
@Override
public String viewAccount(final Integer id) {
synchronized (monitor) {
Account account = this.accounts.get(id);
if (account != null) {
return account.toString();
}
return "Account not found.";
}
}
@Override
public boolean updateAccount(final Integer id, final String name) {
synchronized (monitor) {
Account oldVersion = this.accounts.get(id);
if (oldVersion != null) {
Account updatedAccount = new User(
oldVersion.getAmount(), name, id
);
this.accounts.put(id, updatedAccount);
return true;
}
return false;
}
}
@Override
public boolean delAccount(final Integer id) {
synchronized (monitor) {
Account account = this.accounts.get(id);
if (account != null) {
this.accounts.remove(id);
return true;
}
return false;
}
}
}