What is the output of the following application?.
package mypkg; /* w ww . j a v a 2s. c o m*/ import java.util.*; public class Main<T> { private List<T> data; private boolean foundMatch = false; public Main(List<T> list) { this.data = list; } public void exists(T value,int start, int end) { if(end-start<=1) { foundMatch = foundMatch || value.equals(data.get(start)); } else { final int middle = start + (end-start)/2; new Thread(() -> exists(value,start,middle)).run(); new Thread(() -> exists(value,middle,end)).run(); } } public static void main(String[] a) throws Exception { List<Integer> data = Arrays.asList(1,2,3,4,5,6); Main<Integer> t = new Main<Integer>(data); t.exists(5, 0, data.size()); System.out.print(t.foundMatch); } }
A.
The code attempts to search for a matching element in an array recursively.
While it does not contain any compilation problems, it does contain an error.
Despite creating Thread instances, it is not a multi-threaded program.
Calling run()
on a Thread runs the process as part of the current thread.
To be a multi-threaded execution, it would need to instead call the start()
method.
For this reason, the code completes synchronously, waiting for each method call to return before moving on to the next and printing true at the end of the execution, making Option A the correct answer.
On the other hand, if start()
had been used, then the application would be multi-threaded but then the result may not be ready by the time the println()
method is called, resulting in a value that cannot be predicted ahead of time.
Option D would be the correct answer.