1.Assuming this class is accessed by only a single thread at a time, what
is the result of calling the countIceCreamFlavors() method?
import java.util.stream.LongStream;
public class Flavors {
private static int counter;
public static void countIceCreamFlavors() {
counter = 0;
Runnable task = () -> counter++;
LongStream.range(0, 500)
.forEach(m -> new Thread(task).run());
System.out.println(counter);
} }
A) The method consistently prints 500
2.Assuming one minute is enough time for all the threads within this
program to complete, what are the possible results of executing the
following program?
public class RocketShip {
private volatile int fuel;
private void launch(int checks) {
var p = new ArrayList();
for (int i = 0; i < checks; i++)
p.add(new Thread(() -> fuel++));
p.forEach(Thread::interrupt);
p.forEach(Thread::start);
p.forEach(Thread::interrupt);
}
public static void main(String[] args) throws Exception {
var ship = new RocketShip();
ship.launch(100);
Thread.sleep(60*1000);
System.out.print(ship.fuel);
} }
Each correct answer represents a complete solution. Choose all that apply.
A) It prints a number less than 100.
It prints 100.
3.Which of the following statements about the Callable call() and Runnable
run() methods are correct?
Each correct answer represents a complete solution. Choose all that apply.
A) Both can throw unchecked exceptions
Both can be implemented with lambda expressions.
Callable returns a generic type.
4.Which lines need to be changed to make the code compile?
ExecutorService service = // w1
Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay(() -> {
System.out.println(“Open Zoo”);
return null; // w2
}, 0, 1, TimeUnit.MINUTES);
var result = service.submit(() -> // w3
System.out.println(“Wake Staff”));
System.out.println(result.get()); // w4
Each correct answer represents a part of the solution. Choose all that apply.
A) Line w1
Line w2
5.What happens when a new task is submitted to an ExecutorService in
which no threads are available?
A) The executor adds the task to an internal queue and completes when
there is an available thread.
6.Assuming each call to takeNap() takes five seconds to execute without
throwing an exception, what is the expected result of executing the
following code snippet?
ExecutorService service = Executors.newFixedThreadPool(4);
try {
service.execute(() -> takeNap());
service.execute(() -> takeNap());
service.execute(() -> takeNap());
} finally {
service.shutdown();
}
service.awaitTermination(2, TimeUnit.SECONDS);
System.out.println(“DONE!”);
A) It will pause for 2 seconds and then print DONE!.
7.Which of the following are valid Callable expressions?
Each correct answer represents a complete solution. Choose all that apply.
A) () -> 5
() -> “The” + “Zoo”
() -> {System.out.println(“Giraffe”); return 10;}
8.What is the result of executing the following program?
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class PrintCounter {
static int count = 0;
public static void main(String[] args) throws
InterruptedException, ExecutionException {
var service = Executors.newSingleThreadExecutor();
try {
var r = new ArrayList<Future<?>>();
IntStream.iterate(0,i -> i+1).limit(5).forEach(
i -> r.add(service.execute(() -> {count++;})) // n1
);
for(Future result : r) {
System.out.print(result.get()+” “); // n2
}
} finally { service.shutdown(); }
} }
A) The code will not compile because of line n1.
9.Assuming an implementation of the performCount() method is provided
prior to runtime, which of the following are possible results of executing
the following application?
import java.util.*;
import java.util.concurrent.*;
public class CountZooAnimals {
public static void performCount(int animal) {
// IMPLEMENTATION OMITTED
}
public static void printResults(Future f) {
try {
System.out.println(f.get(1, TimeUnit.DAYS)); // o1
} catch (Exception e) {
System.out.println(“Exception!”);
}
}
public static void main(String[] args) throws Exception {
final var r = new ArrayList>();
ExecutorService s = Executors.newSingleThreadExecutor();
try {
for(int i = 0; i < 10; i++) {
final int animal = i;
r.add(s.submit(() -> performCount(animal))); // o2
}
r.forEach(f -> printResults(f));
} finally { s.shutdown(); }
} }
Each correct answer represents a complete solution. Choose all that apply.
A) It outputs a null value 10 times.
It outputs Exception! 10 times.
10.What statement about the following code is true?
var value1 = new AtomicLong(0);
final long[] value2 = {0};
IntStream.iterate(1, i -> 1).limit(100).parallel()
.forEach(i -> value1.incrementAndGet());
IntStream.iterate(1, i -> 1).limit(100).parallel()
.forEach(i -> ++value2[0]);
System.out.println(value1+” “+value2[0]);
A) The output cannot be determined ahead of time.
11.Which statement about methods in ReentrantLock is correct?
A) None of these.
12.What are the results of executing the following code?
import java.util.concurrent.; import java.util.stream.;
public class PrintConstants {
public static void main(String[] args) {
var s = Executors.newScheduledThreadPool(10);
DoubleStream.of(3.14159,2.71828) // b1
.forEach(c -> s.submit( // b2
() -> System.out.println(10*c))); // b3
s.execute(() -> System.out.println(“Printed”));
} }
Each correct answer represents a complete solution. Choose all that apply.
A) It compiles, but the output cannot be determined ahead of time.
It compiles but waits forever at runtime
13.Assuming one minute is enough time for the tasks submitted to
the service executor to complete, what is the result of executing
countSheep()?
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class BedTime {
private AtomicInteger s1 = new AtomicInteger(0); // w1
private int s2 = 0;
private void countSheep() throws InterruptedException {
var service = Executors.newSingleThreadExecutor(); // w2
try {
for (int i = 0; i < 100; i++)
service.execute(() -> {
s1.getAndIncrement(); s2++; }); // w3
Thread.sleep(60*1000);
System.out.println(s1 + ” ” + s2);
} finally { service.shutdown(); }
}
public static void main(String… nap) throws InterruptedException {
new BedTime().countSheep();
} }
A) The method consistently prints 100 100.
14.What is the result of executing the following code?
import java.util.concurrent.; import java.util.stream.;
public class StockRoomTracker {
public static void await(CyclicBarrier cb) { // j1
try { cb.await(); } catch (Exception e) {}
}
public static void main(String[] args) {
var cb = new CyclicBarrier(10,
() -> System.out.println(“Stock Room Full!”)); // j2
IntStream.iterate(1, i -> 1).limit(9).parallel()
.forEach(i -> await(cb)); // j3
} }
A) It compiles but waits forever at runtime.
15.What statements about the following class definition are true?
public final class TicketManager {
private int tickets;
private static TicketManager instance;
private TicketManager() {}
static synchronized TicketManager getInstance() { // k1
if (instance==null) instance = new TicketManager(); // k2
return instance;
}
public int getTicketCount() { return tickets; }
public void addTickets(int value) {tickets += value;} // k3
public void sellTickets(int value) {
synchronized (this) { // k4
tickets -= value;
} } }
Each correct answer represents a complete solution. Choose all that apply.
A) It compiles without issue.
At most one instance of TicketManager will be created in an application
that uses this class.
16.What is the result of executing the following code snippet?
List lions = new ArrayList<>(List.of(1,2,3));
List tigers = new CopyOnWriteArrayList<>(lions);
Set bears = new ConcurrentSkipListSet<>();
bears.addAll(lions);
for(Integer item: tigers) tigers.add(4); // x1
for(Integer item: bears) bears.add(5); // x2
System.out.println(lions.size() + ” ” + tigers.size()
” ” + bears.size());
A) It outputs 3 6 4.
17.What statements about the following code snippet are true?
Object o1 = new Object();
Object o2 = new Object();
var service = Executors.newFixedThreadPool(2);
var f1 = service.submit(() -> {
synchronized (o1) {
synchronized (o2) { System.out.print(“Tortoise”); }
}
});
var f2 = service.submit(() -> {
synchronized (o2) {
synchronized (o1) { System.out.print(“Hare”); }
}
});
f1.get();
f2.get();
Each correct answer represents a complete solution. Choose all that apply.
A) If the code does output anything, the order cannot be determined.
The code compiles but may produce a deadlock at runtime.
18.Fill in the blanks: __ occur(s) when two or more threads
are blocked forever but both appear active. _ occur(s) when two
or more threads try to complete a related task at the same time,
resulting in invalid or unexpected data.
A) Livelock, Race conditions
19.Given that the sum of the numbers from 1 (inclusive) to 10
(exclusive) is 45, what are the possible results of executing the
following program?
import java.util.concurrent.locks.*;
import java.util.stream.*;
public class Bank {
private Lock vault = new ReentrantLock();
private int total = 0;
public void deposit(int value) {
try {
vault.tryLock();
total += value;
} finally { vault.unlock(); }
}
public static void main(String[] unused) {
var bank = new Bank();
IntStream.range(1, 10).parallel()
.forEach(s -> bank.deposit(s));
System.out.println(bank.total);
} }
Each correct answer represents a complete solution. Choose all that apply.
A) 45 is printed.
An exception is thrown.
20.Which statements about the following code are correct?
var data = List.of(2,5,1,9,8);
data.stream().parallel()
.mapToInt(s -> s)
.peek(System.out::print)
.forEachOrdered(System.out::print);
Each correct answer represents a complete solution. Choose all that apply.
A) I.The peek() method will print the entries in an order that cannot be
determined ahead of time.
II.The forEachOrdered() method will print the entries in the original order:
25198.
21.Which statement about the following code snippet is correct?
var cats = Stream.of(“leopard”, “lynx”, “ocelot”, “puma”)
+ ” ” + data.get(true).size());
.parallel();
var bears = Stream.of(“panda”,”grizzly”,”polar”).parallel();
var data = Stream.of(cats,bears).flatMap(s -> s)
.collect(Collectors.groupingByConcurrent(
s -> !s.startsWith(“p”)));
A) It outputs 3 4.
22.Given the following code snippet, which options correctly create a
parallel stream?
var c = new ArrayList();
var s = c.stream();
var p = _____;
Each correct answer represents a complete solution. Choose all that apply.
A) c.parallelStream()
s.parallel()
23.What statement about the following code is true?
Integer i1 = List.of(1, 2, 3, 4, 5).stream().findAny().get();
synchronized(i1) { // y1
Integer i2 = List.of(6, 7, 8, 9, 10)
.parallelStream()
.sorted()
.findAny().get(); // y2
System.out.println(i1 + ” ” + i2);
A) The output cannot be determined ahead of time.
24.What statement about the following code is true?
System.out.print(List.of(“duck”,”flamingo”,”pelican”)
.parallelStream().parallel() // q1
.reduce(0,
(c1, c2) -> c1.length() + c2.length(), // q2
(s1, s2) -> s1 + s2)); // q3
A) The code will not compile because of line q2.
25.Given the following code snippet and blank lines on p1 and p2,
which values guarantee that 1 is printed at runtime?
var data = List.of(List.of(1,2),
List.of(3,4),
List.of(5,6));
data. // p1
.flatMap(s -> s.stream())
._ // p2
.ifPresent(System.out::print);
Each correct answer represents a complete solution. Choose all that apply.
A) stream() on line p1, findFirst() on line p2
parallelStream() on line p1, findFirst() on line p2
Other Links:
Statistics Quiz
Networking Quiz
See other websites for quiz:
Check on QUIZLET
Check on CHEGG