How rude!
at runtime?
public class Speaking {
void talk() {
try {
Thread.sleep(10_000);
} catch (InterruptedException e) {
System.out.println("How rude!");
} }
public static void main(String[] args) {
var s = new Speaking();
var t = new Thread(() -> s.talk());
t.run();
t.interrupt();
t.interrupt();
t.interrupt();
} }
Callable c = new Callable() {
public Object run() {
System.out.print("X");
return 10;
}
};
var s = Executors.newScheduledThreadPool(1);
for(int i=0; i<10; i++) {
Future f = s.submit(c);
f.get();
}
s.shutdown();
System.out.print("Done!");
XXXXXXXXXXDone!
Done!XXXXXXXXXX
ExecutorService
instance? (Choose two.)
execute(Callable)
shutdownNow()
submit(Runnable)
exit()
submit(Callable)
execute(Runnable)
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class Luck {
private AtomicBoolean coin = new AtomicBoolean(false);
void flip() {
coin.getAndSet(!coin.get());
}
public static void main(String[] gamble) throws Exception {
var luck = new Luck();
ExecutorService s = Executors.newCachedThreadPool();
for(int i=0; i<1000; i++) {
s.execute(() -> luck.flip());
}
s.shutdown();
Thread.sleep(5000);
System.out.println(luck.coin.get());
} }
false
true
Callable
expression and pass it to an instance of an Executor
.Thread
and override the start()
method.Runnable
lambda expression and pass it to a Thread
constructor.Runnable
class that overrides the begin()
method.import java.util.*;
public class Dance {
int count = 0;
synchronized int step() { return count++; }
public static void main(String[] args) throws InterruptedException {
var waltz = new Dance();
var dancers = new ArrayList<Thread>();
for(int i=0; i<10; i++)
dancers.add(new Thread(() -> waltz.step()));
for(Thread dancer : dancers)
dancer.start();
dancers.forEach(d -> d.interrupt());
Thread.sleep(5_000);
System.out.print(waltz.count);
} }
10
.10
.10
or a number less than 10
.Locked!
expected to be printed?
import java.util.concurrent.locks.*;
public class Padlock {
private Lock lock = new ReentrantLock();
public void lockUp() {
if (lock.tryLock()) {
lock.lock();
System.out.println("Locked!");
lock.unlock();
}
}
public static void main(String… unused) throws Exception {
var gate = new Padlock();
for(int i=0; i<5; i++) {
new Thread(() -> gate.lockUp()).start();
Thread.sleep(1_000);
} } }
import java.util.concurrent.atomic.*;
import java.util.stream.*;
public class TicketTaker {
long ticketsSold;
final AtomicInteger ticketsTaken;
public TicketTaker() {
ticketsSold = 0;
ticketsTaken = new AtomicInteger(0);
}
public void performJob() {
IntStream.iterate(1, p -> p+1)
.parallel()
.limit(100)
.forEach(i -> ticketsTaken.getAndIncrement());
IntStream.iterate(1, q -> q+1)
.parallel()
.limit(500)
.forEach(i -> ++ticketsSold);
System.out.print(ticketsTaken+" "+ticketsSold);
}
public static void main(String[] matinee) {
new TicketTaker().performJob();
} }
TicketTaker
constructor does not compile.performJob()
method does not compile.100
.500
.ConcurrentModificationException
is thrown at runtime.original
array, how many of the following for
statements result in an exception at runtime, assuming each is executed independently?
var original = List.of(1,2,3,4,5);
var copy1 = new CopyOnWriteArrayList<Integer>(original);
for(Integer w : copy1)
copy1.remove(w);
var copy2 = Collections.synchronizedList(original);
for(Integer w : copy2)
copy2.remove(w);
var copy3 = new ArrayList<Integer>(original);
for(Integer w : copy3)
copy3.remove(w);
var copy4 = new ConcurrentLinkedQueue<Integer>(original);
for(Integer w : copy4)
copy4.remove(w);
import java.util.stream.*;
public class Bull {
void charge() {
IntStream.range(1,6)
.parallel()
.forEachOrdered(System.out::print);
}
public static void main(String[] args) {
var b = new Bull();
b.charge();
} }
12345
54321
3: public class TpsReport {
4: public void submitReports() {
5: var s = Executors.newCachedThreadPool();
6: Future bosses = s.submit(() -> System.out.print("1"));
7: s.shutdown();
8: System.out.print(bosses.get());
9: }
10: public static void main(String[] memo) {
11: new TpsReport().submitReports();
12: } }
null
1null
1
static
methods do not exist in the Executors
class? (Choose two.)
newFixedScheduledThreadPool()
newThreadPool()
newFixedThreadPool(int)
newSingleThreadExecutor()
newScheduledThreadPool(int)
newSingleThreadScheduledExecutor()
Ready
at runtime?
package parade;
import java.util.concurrent.*;
public class CartoonCat {
private void await(CyclicBarrier c) {
try {
c.await();
} catch (Exception e) {}
}
public void march(CyclicBarrier c) {
var s = Executors.newSingleThreadExecutor();
for(int i=0; i<12; i++)
s.execute(() -> await(c));
s.shutdown();
}
public static void main(String… strings) {
new CartoonCat().march(new CyclicBarrier(4,
() -> System.out.println("Ready")));
} }
CyclicBarrier
that has a barrier limit of five threads. Which static
method in ExecutorService
should you use to obtain it?
newSingleThreadExecutor()
newSingleThreadScheduledExecutor()
newCachedThreadPool()
newFixedThreadPool(2)
import java.util.concurrent.atomic.*;
import java.util.stream.*;
public class Circus {
private static int seal = 0;
private static volatile int tiger = 0;
private static AtomicInteger lion = new AtomicInteger(0);
public static void main(String[] tent) {
Stream.iterate(0, x -> x + 1)
.parallel()
.limit(100)
.forEach(q -> {seal++; tiger++; lion.incrementAndGet();});
System.out.println(seal + "," + tiger + ","+ lion);
} }
100
.100
. 100
.100
.100
.100
.import java.util.*;
import java.util.concurrent.*;
public class Race {
ExecutorService service = Executors.newFixedThreadPool(8);
public static int sleep() {
try { Thread.sleep(1000); } catch (Exception e) {}
return 1;
}
public void hare() {
try {
Callable<Integer> c = () -> sleep();
final var r = List.of(c,c,c);
var results = service.invokeAll(r);
System.out.println("Hare won the race!");
} catch (Exception e) {e.printStackTrace();}
}
public void tortoise() {
try {
Callable<Integer> c = () -> sleep();
final var r = List.of(c,c,c);
Integer result = service.invokeAny(r);
System.out.println("Tortoise won the race!");
} catch (Exception e) {e.printStackTrace();}
}
public static void main(String[] p) throws Exception {
var race = new Race();
race.service.execute(() -> race.hare());
race.service.execute(() -> race.tortoise());
} }
Hare won the race!
is printed first.Tortoise won the race!
is printed first. ConcurrentSkipList
ConcurrentSkipListSet
CopyOnWriteArrayList
ConcurrentSkipListMap
ConcurrentLinkedQueue
LinkedBlockingQueue
package taxes;
import java.util.concurrent.*;
public class Accountant {
public static void completePaperwork() {
System.out.print("[Filing]");
}
public static double getPi() {
return 3.14159;
}
public static void main(String[] args) throws Exception {
ExecutorService x = Executors.newSingleThreadExecutor();
Future<?> f1 = x.submit(() -> completePaperwork());
Future<Object> f2 = x.submit(() -> getPi());
System.out.print(f1.get()+" "+f2.get());
x.shutdown();
} }
[Filing]
[Filing]3.14159
[Filing]null 3.14159
f1
does not compile.f2
does not compile.import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class Clock {
private AtomicLong bigHand = new AtomicLong(0);
void incrementBy10() {
bigHand.getAndSet(bigHand.get() + 10);
}
public static void main(String[] c) throws Exception {
var smartWatch = new Clock();
ExecutorService s = Executors.newCachedThreadPool();
for(int i=0; i<100; i++) {
s.submit(() -> smartWatch.incrementBy10()).get();
}
s.shutdown();
s.awaitTermination(10, TimeUnit.SECONDS);
System.out.println(smartWatch.bigHand.get());
} }
incrementBy10()
method is thread-safe.incrementBy10()
method is not thread-safe.1000
on every execution.package jokes;
import java.util.concurrent.*;
public class Riddle {
public void sleep() {
try { Thread.sleep(5000); } catch (Exception e) {}
}
public String getQuestion(Riddle r) {
synchronized {
sleep();
if(r != null) r.getAnswer(null);
return "How many programmers does it take "
+ "to change a light bulb?";
} }
public synchronized String getAnswer(Riddle r) {
sleep();
if(r != null) r.getAnswer(null);
return "None, that's a hardware problem";
}
public static void main(String… ununused) {
var r1 = new Riddle();
var r2 = new Riddle();
var s = Executors.newFixedThreadPool(2);
s.submit(() -> r1.getQuestion(r2));
s.execute(() -> r2.getAnswer(r1));
s.shutdown();
} }
ScheduledExecutorService
method can result in the same action being executed by two threads at the same time?
scheduleAtFixedDelay()
scheduleAtFixedRate()
scheduleWithFixedDelay()
scheduleAtSameRate()
scheduleWithRate()
package olympics;
import java.util.concurrent.*;
public class Athlete {
int stroke = 0;
public synchronized void swimming() {
stroke++;
}
private int getStroke() {
synchronized(this) { return stroke; }
}
public static void main(String… laps) {
ExecutorService s = Executors.newFixedThreadPool(10);
Athlete a = new Athlete();
for(int i=0; i<1000; i++) {
s.execute(() -> a.swimming());
}
s.shutdown();
System.out.print(a.getStroke());
} }
1000
stroke
is not written in a thread-safe manner and a write may be lost.int
variable incorrectly reporting the number of times an operation was performedpackage my;
import java.util.*;
public class ThreadSafeList {
private List<Integer> data = new ArrayList<>();
public synchronized void addValue(int value) {
data.add(value);
}
public int getValue(int index) {
return data.get(index);
}
public int size() {
synchronized(ThreadSafeList.class) {
return data.size();
} } }
size()
method.getValue()
method.print2()
method, produce the same output as the print1()
method? Assume the input arguments for each represent the same non-null
numeric value.
public static synchronized void print1(int counter) {
System.out.println(counter--);
System.out.println(++counter);
}
public static synchronized void print2(AtomicInteger counter) {
System.out.println(counter._________________);
System.out.println(counter._________________);
}
decrementAndGet()
and getAndIncrement()
decrementAndGet()
and incrementAndGet()
getAndDecrement()
and getAndIncrement()
getAndDecrement()
and incrementAndGet()
package bears;
import java.util.*;
public class Bounce {
public static void main(String… legend) {
List.of(1,2,3,4).stream()
.forEach(System.out::println);
List.of(1,2,3,4).parallel()
.forEach(System.out::println);
List.of(1,2,3,4).parallel()
.forEachOrdered(System.out::println);
} }
11: ScheduledExecutorService t = Executors
12: .newSingleThreadScheduledExecutor();
13: Future result = t.execute(System.out::println);
14: t.invokeAll(null);
15: t.scheduleAtFixedRate(() -> {return;},5,TimeUnit.MINUTES);
W
at runtime?
package crew;
import java.util.concurrent.*;
import java.util.stream.*;
public class Boat {
private void waitTillFinished(CyclicBarrier c) {
try {
c.await();
System.out.print("W");
} catch (Exception e) {}
}
public void row(ExecutorService s) {
var cb = new CyclicBarrier(5);
IntStream.iterate(1, i-> i+1)
.limit(12)
.forEach(i -> s.submit(() -> waitTillFinished(cb)));
}
public static void main(String[] oars) {
ExecutorService service = null;
try {
service = Executors.newCachedThreadPool();
new Boat().row(service);
} finally {
service.isShutdown();
} } }
Boat
class from the previous question, what is the final state of the application?
ExecutorService
is never shut down.p1
and p2
is correct?
var db = Collections.synchronizedList(new ArrayList<>());
IntStream.range(1,6)
.parallel()
.map(i -> {db.add(i); return i;})
.forEachOrdered(System.out::print); // p1
System.out.println();
db.forEach(System.out::print); // p2
ConcurrentModificationException
at runtime.TV Time
expected to be printed? Assume 10 seconds is enough time for each task created by the program to complete.
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class Television {
private static Lock myTurn = new ReentrantLock();
public void watch() {
try {
if (myTurn.lock(5, TimeUnit.SECONDS)) {
System.out.println("TV Time");
myTurn.unlock();
}
} catch (InterruptedException e) {}
}
public static void main(String[] t) throws Exception {
var newTv = new Television();
for (int i = 0; i < 3; i++) {
new Thread(() -> newTv.watch()).start();
Thread.sleep(10*1000);
}
} }
original
array, how many of the following for
statements enter an infinite loop at runtime, assuming each is executed independently?
var original = new ArrayList<Integer>(List.of(1,2,3));
var copy1 = new ArrayList<Integer>(original);
for(Integer q : copy1)
copy1.add(1);
var copy2 = new CopyOnWriteArrayList<Integer>(original);
for(Integer q : copy2)
copy2.add(2);
var copy3 = new LinkedBlockingQueue<Integer>(original);
for(Integer q : copy3)
copy3.offer(3);
var copy4 = Collections.synchronizedList(original);
for(Integer q : copy4)
copy4.add(4);
ExecutorService
method guarantees all running tasks are stopped in an orderly fashion?
shutdown()
shutdownNow()
halt()
shutdownAndTerminate()
import java.util.concurrent.*;
public class Bank {
static int cookies = 0;
public synchronized void deposit(int amount) {
cookies += amount;
}
public static synchronized void withdrawal(int amount) {
cookies -= amount;
}
public static void main(String[] amount) throws Exception {
var teller = Executors.newScheduledThreadPool(50);
Bank bank = new Bank();
for(int i=0; i<25; i++) {
teller.submit(() -> bank.deposit(5));
teller.submit(() -> bank.withdrawal(5));
}
teller.shutdown();
teller.awaitTermination(10, TimeUnit.SECONDS);
System.out.print(bank.cookies);
} }
0
125
-125
import java.util.*;
public class SearchList<T> {
private List<T> data;
private boolean foundMatch = false;
public SearchList(List<T> list) {
this.data = list;
}
public void exists(T v,int start, int end) {
if(end-start==0) {}
else if(end-start==1) {
foundMatch = foundMatch || v.equals(data.get(start));
} else {
final int middle = start + (end-start)/2;
new Thread(() -> exists(v,start,middle)).run();
new Thread(() -> exists(v,middle,end)).run();
}
}
public static void main(String[] a) throws Exception {
List<Integer> data = List.of(1,2,3,4,5,6);
SearchList<Integer> t = new SearchList<Integer>(data);
t.exists(5, 0, data.size());
System.out.print(t.foundMatch);
} }
true
false
q1
and q2
is correct?
var mitchsWorkout = new CopyOnWriteArrayList<Integer>();
List.of(1,5,7,9).stream().parallel()
.forEach(mitchsWorkout::add);
mitchsWorkout
.forEachOrdered(System.out::print); // q1
List.of(1,5,7,9).stream().parallel()
.forEachOrdered(System.out::print); // q2
ConcurrentModificationException
at runtime.import java.util.concurrent.atomic.*;
import java.util.stream.*;
public class Moon {
private volatile AtomicLong green = new AtomicLong(0);
private volatile int cheese = 0;
private volatile int rocket = 0;
private void takeOff() {
Stream.iterate(0, x -> x + 1).parallel().limit(1000).forEach(q -> {
green.getAndIncrement();
cheese++;
synchronized (this) {
++rocket;
}
});
System.out.println(green + "," + cheese + "," + rocket);
}
public static void main(String[] tent) {
new Moon().takeOff();
} }
1000
.1000
. 1000
.1000
.1000
.1000
.var drink = List.of("coke", "soda", "pop");
System.out.print(drink.parallelStream()
.parallel()
.reduce(0, (c1, c2) -> c1 + c2.length(), (s1, s2) -> s1 + s2));
System.out.print(drink.stream()
.reduce(0, (c1, c2) -> c1 + c2.length(), (s1, s2) -> s1 + s2));
11
.11
.11
.11
.18.119.17.64