Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class UserStorage implements Storage {
- // По идее все вопросы по синхронизации ConcurrentHashMap должна снимать.
- private Map<Integer, Account> accounts = new ConcurrentHashMap<>();
- @Override
- public boolean addAccount(final Account account) {
- final Account a = this.accounts.get(account.getId());
- if (a != null) {
- return false;
- }
- this.accounts.put(account.getId(), account);
- return true;
- }
- }
- public class Consumer {
- private Storage storage = new UserStorage();
- public boolean addAccount(BigDecimal amount, String name, Integer id) throws InterruptedException {
- ThreadAdd thread = new ThreadAdd(amount, name, id);
- thread.start();
- //thread.join(); // вот этот join мне все портит без него не работает, а с ним однопоточный код получается.
- return thread.added;
- }
- // класс потока
- private class ThreadAdd extends Thread {
- private boolean added;
- private BigDecimal amount;
- private String name;
- private Integer id;
- private ThreadAdd(BigDecimal amount, String name, Integer id) {
- this.amount = amount;
- this.name = name;
- this.id = id;
- }
- @Override
- public void run() {
- this.add();
- }
- private void add() {
- Account account = new User(this.amount, this.name, this.id);
- this.added = Consumer.this.storage.addAccount(account);
- }
- }
- }
- @Test
- public void whenAddWithOriginalIdThenAddAccountReturnTrue() throws InterruptedException {
- List<Boolean> result = new LinkedList<>();
- for (int i = 0; i < 100; i++) {
- result.add(consumer.addAccount(new BigDecimal("32"), "name", i));
- }
- result.forEach(Assert::assertTrue);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement