-3

I have a method

public boolean contains(int valueToFind, List<Integer> list) {
//
}

How can I split the array into x chunks? and have a new thread for searching every chunk looking for the value. If the method returns true, I would like to stop the other threads from searching.

I see there are lots of examples for simply splitting work between threads, but how I do structure it so that once one thread returns true, all threads and return that as the answer?

I do not want to use parallel streams for this reason (from source):

If you do, please look at the previous example again. There is a big error. Do you see it? The problem is that all parallel streams use common fork-join thread pool, and if you submit a long-running task, you effectively block all threads in the pool. Consequently, you block all other tasks that are using parallel streams. Imagine a servlet environment, when one request calls getStockInfo() and another one countPrimes(). One will block the other one even though each of them requires different resources. What's worse, you can not specify thread pool for parallel streams; the whole class loader has to use the same one.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
  • I think you dont understand the problem. You dont want that "all threads return". You basically ignore all the other threads. But note: unless this is for learning purposes, you should just go with the streams solution given to you. And I hope you understand that your list needs to be really large in order to gain a "speedup" by using multiple threads. – GhostCat Feb 10 '21 at 16:24

1 Answers1

1

You could use the built-in Stream API:

//For a List
public boolean contains(int valueToFind, List<Integer> list) {
   return list.parallelStream().anyMatch(Integer.valueOf(valueToFind)::equals);
}

//For an array
public boolean contains(int valueToFind, int[] arr){
   return Arrays.stream(arr).parallel().anyMatch(x -> x == valueToFind);
}

Executing Streams in Parallel:

You can execute streams in serial or in parallel. When a stream executes in parallel, the Java runtime partitions the stream into multiple substreams. Aggregate operations iterate over and process these substreams in parallel and then combine the results.

When you create a stream, it is always a serial stream unless otherwise specified. To create a parallel stream, invoke the operation Collection.parallelStream.
Unmitigated
  • 76,500
  • 11
  • 62
  • 80