-1

I have simple loop:

   List<String> results = new ArrayList<String>();
            for (int i = 0; i < 100000000; i++) {
               results.add("a" + i + "b");
            }

    return results;

must be simple idea- because if I will start to create thread pool, I will spend memory for additional objects, also without java8.

How can I implement simple parallel loop ?

Max Usanin
  • 2,479
  • 6
  • 40
  • 70

3 Answers3

2

The easiest way to speed this up is to create an ArrayList with the size that you need ahead of time. I have no idea why you would need a list like this, but I can only assume that your program is slowing down everytime it has to allocate and copy another array because it ran out of space.

List<String> results = new ArrayList<String>(10000000);
John E.
  • 418
  • 2
  • 10
1

This can't be done parralel for a simple reason: Java doesn't provide an efficient List implementation for concurrent access.

The simplest solution would be to implement an own LinkedList and link several LinkedLists into one, which can be done a lot faster and in parralel. The merge-operation can afterwards be done in O(1).

  • and perform these operations in parallel ? after to merge the LinkedList(s)? – Max Usanin Oct 08 '15 at 19:18
  • @MaxUsanin no fill several LinkedLists in parrallel and merge them afterwards. You'll have to implement the list on your own. –  Oct 08 '15 at 19:23
  • @Kayaman the only list is `CopyOnWriteArrayList` and as for the efficiency: the underlying array is copied on each write, nothing more to be said. –  Oct 08 '15 at 19:25
  • You're right (after the edit) about no `List` implementation besides `CopyOnWriteArrayList`. However considering how vague the question is, he might be able to use for example [ConcurrentLinkedDeque](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedDeque.html). – Kayaman Oct 08 '15 at 19:40
  • I will thumb up for your suggestion, because it sounds like map reduce approach. Thank you. – Max Usanin Oct 08 '15 at 19:44
0

Using Java 8 parallell streams you can do this:

IntStream.range(0, 100000000)
         .parallel()
         .mapToObj(i -> new StringBuilder()
                               .append("a")
                               .append(i)
                               .append("b")
                               .toString())
         .collect(Collectors.toList());

First, IntStream.range(0, 100000000) creates an IntStream with the values 0 to 100000000 (exclusive). Then, the IntStream is made parallel using the parallel method. Then, I use mapToObj in order to make the IntStream into a Stream<String>. At last, the stream will be collected in a List. I also use a StringBuilder to make the string concatenation a bit faster.

marstran
  • 26,413
  • 5
  • 61
  • 67