Nishra Nasar wrote:I would like to know whether i can eligible for OCPJP(Java SE 8 II) without OCAJP (Java SE 8 I) as most of of basic java theories are covered within my HND.
Since order is not guaranteed with parallel streams, methods such as findAny() on parallel streams may result in unexpected behavior. Let’s take a look at the results of findAny() applied to a serial stream:
System.out.print(Arrays.asList(1,2,3,4,5,6).stream().findAny().get());
This code consistently outputs the first value in the serial stream, 1.
With a parallel stream, the JVM can create any number of threads to process the stream. When you call findAny() on a parallel stream, the JVM selects the first thread to finish the task and retrieves its data:
System.out.print(Arrays.asList(1,2,3,4,5,6).parallelStream().findAny().get());
The result is that the output could be 4, 1, or really any value in the stream. You can see that with parallel streams, the results of findAny() are no longer predictable.
What will the following code print?
Object v1 = IntStream.rangeClosed(10, 15)
.boxed()
.filter(x->x>12)
.parallel()
.findAny();
Object v2 = IntStream.rangeClosed(10, 15)
.boxed()
.filter(x->x>12)
.sequential()
.findAny();
System.out.println(v1+":"+v2);
(Note: < and > in the options below denote the possible output and not the sign themselves.)
<An Optional containing 13, 14, or 15>:<An Optional containing 13, 14, or 15>
The second stream is sequential and therefore, ideally, findAny should return the first element. However, findAny is deliberately designed to be non-deterministic. Its API specifically says that it may return any element from the stream. If you want to select the first element, you should use findFirst.
"The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)
1
2
3
Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
Bindurekha Ragu wrote:Thank Paul for your brief post about enthuware.