0

Is it better to use some of thread safe collections ? Scope of the question is only the generation and adding of elements into the list.

public List<BankDetailsDTO> generateBankDetailsDTOs(int amount) {
    List<BankDetailsDTO> result = new ArrayList<>();
    IntStream.range(0, amount).parallel().forEach(index -> {
        result.add(new BankDetailsDTO(bankDetailsDTOCounter.getAndIncrement(),
            faker.company().name(),
            faker.finance().iban(),
            faker.finance().bic(),
            faker.finance().iban()));
        });
        return result;
    }
}

Update Ok this was an bad idea.

    public List<BankDetailsDTO> generateBankDetailsDTOs(int amount) {
        List<BankDetailsDTO> result = Collections.synchronizedList(new ArrayList<>());
        IntStream.range(0, amount).parallel().forEach(index -> {
            result.add(new BankDetailsDTO(bankDetailsDTOCounter.getAndIncrement(),
                    faker.company().name(),
                    faker.finance().iban(),
                    faker.finance().bic(),
                    faker.finance().iban()));
        });
        return result;
    }
Rafa Guillermo
  • 14,474
  • 3
  • 18
  • 54
Tristate
  • 1,498
  • 2
  • 18
  • 38
  • 4
    Short answer: yes, it is wrong. – Kayaman Mar 20 '20 at 13:35
  • 2
    Please read [this](https://stackoverflow.com/questions/2715983/concurrent-threads-adding-to-arraylist-at-same-time-what-happens) also. – Miss Chanandler Bong Mar 20 '20 at 13:36
  • 1
    Why `add`ing inside `forEach` when you can first `map` and then `forEach` or `collect`? – Miss Chanandler Bong Mar 20 '20 at 13:37
  • 1
    This is basically using an `IntStream` to mimic a `for` loop, and making the stream parallel would most likely hurt performance (uses the shared pool, no performance advantage unless there's a large amount of real work to be done). So there's more wrong with this code than just the thread-unsafety. – Kayaman Mar 20 '20 at 13:43
  • @M.S. can you show me an example. – Tristate Mar 20 '20 at 13:52
  • @Tristate example of what? – Miss Chanandler Bong Mar 20 '20 at 13:53
  • @M.S. how to map -> forEach or collect – Tristate Mar 20 '20 at 13:54
  • 1
    `IntStream.range(0, amount).parallel().map(index -> new BankDetailsDTO(...)).forEach(result::add);` – Miss Chanandler Bong Mar 20 '20 at 13:56
  • 1
    [There are may ways](https://stackoverflow.com/a/21526973/2711488) and only the one you've chosen, using `forEach` and `add` requires a thread-safe collection. Since this collection is not really a pre-existing collection but created right before the stream operation, there is no reason to use this non-idiomatic solution. – Holger Mar 23 '20 at 07:35

0 Answers0