Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. public class UserStorage implements Storage {
  2. // По идее все вопросы по синхронизации ConcurrentHashMap должна снимать.
  3. private Map<Integer, Account> accounts = new ConcurrentHashMap<>();
  4.  
  5. @Override
  6. public boolean addAccount(final Account account) {
  7. final Account a = this.accounts.get(account.getId());
  8. if (a != null) {
  9. return false;
  10. }
  11.  
  12. this.accounts.put(account.getId(), account);
  13. return true;
  14. }
  15. }
  16.  
  17.  
  18. public class Consumer {
  19. private Storage storage = new UserStorage();
  20.  
  21. public boolean addAccount(BigDecimal amount, String name, Integer id) throws InterruptedException {
  22. ThreadAdd thread = new ThreadAdd(amount, name, id);
  23. thread.start();
  24. //thread.join(); // вот этот join мне все портит без него не работает, а с ним однопоточный код получается.
  25. return thread.added;
  26. }
  27.  
  28. // класс потока
  29. private class ThreadAdd extends Thread {
  30. private boolean added;
  31.  
  32. private BigDecimal amount;
  33. private String name;
  34. private Integer id;
  35.  
  36. private ThreadAdd(BigDecimal amount, String name, Integer id) {
  37. this.amount = amount;
  38. this.name = name;
  39. this.id = id;
  40. }
  41.  
  42. @Override
  43. public void run() {
  44. this.add();
  45. }
  46.  
  47. private void add() {
  48. Account account = new User(this.amount, this.name, this.id);
  49. this.added = Consumer.this.storage.addAccount(account);
  50. }
  51. }
  52. }
  53.  
  54. @Test
  55. public void whenAddWithOriginalIdThenAddAccountReturnTrue() throws InterruptedException {
  56. List<Boolean> result = new LinkedList<>();
  57. for (int i = 0; i < 100; i++) {
  58. result.add(consumer.addAccount(new BigDecimal("32"), "name", i));
  59. }
  60.  
  61. result.forEach(Assert::assertTrue);
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement