Ch18 Concurrency Flashcards

1
Q

What is a thread?

A

A thread is the smallest unit of execution that can be scheduled by the operating system.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a context switch?

A

A context switch is the process of storing a thread’s current state and later restoring the state of the thread to continue execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a thread priority?

A

A thread priority is a numeric value associated with a thread that is taken into consideration by the thread scheduler when determining which threads should currently be executing.

In java, thread priorities are specified as integer values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What arguments does the Runnable interface take? And what does it return?

A

None and nothing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What package does the Thread class reside in?

A

java.lang

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are two ways to define a task that a Thread instance will execute?

A
  • Providing a Runnable object or lamda expression to the Thread constructor: new Thread(runnable);
  • Create a class that extends Thread and overrides the run() method.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What method is used to start a thread?

A

start()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What exception can Thread.sleep() throw?

A

InterruptedException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

In what package does the Executor class reside in?

A

java.util.concurrent

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What method should be called once you have finished using a thread executor?

A

shutdown()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does the executor’s shutdown() method do?

A

Rejects any new task submitted to the thread executor while continuing to execute any previously submitted tasks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What method can we call to check if shutdown() was called and the thread executor has completed all active tasks?

A

isTerminated()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What method can we call to check if shutdown() was called on a thread executor?

A

isShutDown()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What method can we call on a thread executor to attempt to cancel all running and upcoming tasks?

A

shutdownNow()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the thread executor method shutdownNow() do and return?

A

It will attempt to cancel all running and discard all upcoming tasks, and return a List of all tasks that were submitted but never started.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What thread executor method is available to execute a Runnable and return void? (fire-and-forget)

A

execute(runnable)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What thread executor method is available to execute a Runnable and return a Future to determine wether the task is complete?

A

submit(runnable)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What thread executor method is available to execute a Callable and return a Future to determine wether the task is complete?

A

submit(callable)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What thread executor method is available to execute a list of tasks and waits for all tasks to be complete and returns a list of Future instances?

A

invokeAll(collection)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What thread executor method is available to execute a list of tasks and waits for any of the tasks to be complete and returns a Future instance of that task?

A

invokeAny(collection)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the advantage of using submit() over execute()?

A

submit() is equal to execute() except that it has a return object that can be used to track the result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What Future method is available to check to see if the task was completed?

A

isDone()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What Future method is available to check to see if the task was cancelled?

A

isCancelled()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What Future method is available to attempt to cancel a a task? What does it return?

A

cancel()

Returns true if cancelling was succesful or false if the task could not be cancelled or was completed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What Future method is available to get the result of a task, while waiting until it is available?

A

get()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What Future method is available to get the result of a task, with a timeout of 1 second? What happends when the timeout is reached?

A

get(1, TimeUnit.SECONDS)

it will throw a TimeoutException if the timeout was reached.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What package does the Callable interface reside in?

A

java.util.concurrent

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is the method signature of the interface Callable?

A

call()

29
Q

What is the difference between a Runnable and a Callable?

A
  • Runnable has a run() method, Callable has a call() method.
  • run() returns void, while call() returns a generic object.
  • call() can throw a checked exception.
30
Q

How can we wait for all tasks to finish in an executor?

A

using the awaitTermination(long timeout, TimeUnit unit) method.

31
Q

What method should be called first before calling awaitTermination(long timeout, TimeUnit unit)? why?

A

shutdown()

If awaitTermination() is called before shutdown() within the same thread, that thread will wait the full timeout value sent with awaitTermination()

32
Q

What does the method awaitTermination return?

A

It returns true if this executor terminated and false if the timeout elapsed before termination

33
Q

Given the following code, in what order are the results printed?

ExecutorService service = null;
try {
System.out.println(“Start”);
service = Executors.newSingleThreadExecutor();
Callable c = () -> “result!”;
Future result = service.submit(c);
System.out.println(result.get());
System.out.println(“End”);
} finally {
if (service != null) service.shutdown();
}

A

Start
result!
End

The get() method waits endlessly until the result is available, thus always printing ‘result!’ before ‘End’.

34
Q

What interface can be used to schedule tasks at some future time or at an interval?

A

ScheduledExecutorService

35
Q

How can we create a new ScheduledExecutorService?

ScheduledExecutorService service = …

A

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

36
Q

What methods does the ScheduledExecutorService have?

A
  • schedule(Callable, long delay, TimeUnit)
    schedules and executes a Callable task after the given delay
  • schedule(Runnable, long delay, TimeUnit)
    schedules and executes a Runnable task after the given delay
  • scheduleAtFixedRate(Runnable, long initialDelay, long period, TimeUnit)
    Creates and executes a Runnable task after the given initial delay, creating a new task every period value that passes.
  • scheduleWithFixedDelay(Runnable, long initialDelay, long delay, TimeUnit)
    Creates and executes a Runnable task after the given initial delay and subsequently with the given delay between the termination of one execution and the commencement of the next.
37
Q

Complete the following code to execute the task after 10 minutes.

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
Runnable task = () -> System.out.println(“Hello World”);
ScheduledFuture> result = …

A

service.schedule(task, 10, TImeUnit.MINUTES);

38
Q

Which ExecutorService implementations use a thread pool?

A
  • CachedThreadPool
  • FixedThreadPool
  • ScheduledThreadPool
39
Q

What is the ExecutorService: FixedThreadPool?

A

An ExecutorService that creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.

40
Q

What is the ScheduledExecutorService: ScheduledThreadPool?

A

A ScheduledExecutorService that creates a thread pool that can schedule commands to run after a given delay or to execute periodically.

41
Q

Create a FixedThreadPool such that it behaves similarly to a SingleThreadExecutor.

A

ExecutorService service = Executors.newFixedThreadPool(1);

1 thread = same as SingleThreadExecutor.

42
Q

What command is often used to determine the appropriate pool size?

A

Runtime.getRuntime().availableProcessors()

43
Q

What is a race condition?

A

The unexpected result of two tasks executing at the same time.

44
Q

What atomic classes are available, such that reading and updating the value is thread-safe?

A
  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
45
Q

How can we make the following variable thread-safe such that it won’t produce a race condition?

private int sheepCount = 0;

A

replace int by AtomicInteger

private AtomicInteger sheepCount = new AtomicInteger(0);

46
Q

What Java types can be used in a synchronized statement?

A

Any Object

47
Q

Given the class Test and using the following code, how can we apply synchronization on a static method?

public static void printDaysOfWork() {
System.out.print(“test”);
}

A

public static void printDaysOfWork() {
synchronized(Test.class) {
System.out.print(“test”);
}
}

or

public static synchronized void printDaysOfWork() {
System.out.print(“test”);
}

48
Q

What is the equivalent of the following code, using the Lock interface?

Object object = new Object();
synchronized(object) {
// code
}

A

Lock lock = new ReentrantLock();
try {
lock.lock();
// code
} finally {
lock.unlock();
}

49
Q

What is the Lock implementation class ReentantLock?

A

The ReentrantLock class ensures that once a thread has called lock() and obtained the lock, all other threads that call lock() must wait until the first thread calls unlock().

50
Q

What happens when you want to release a lock (lock.unlock()) that no thread has?

A

It will throw an IllegalMonitorStateException.

51
Q

What methods does the Lock interface contain?

A
  • void lock()
    requests a lock and blocks until lock is acquired
  • void unlock()
    releases a lock
  • boolean tryLock()
    requests a lock and returns immediately. Returns a boolean indicating wether the lock was successfully acquired.
  • boolean tryLock(long, TimeUnit)
    requests a lock and blocks up to the specified time until lock is required. Returns a boolean indicating wether the lock was successfully acquired.
52
Q

The ReentrantLock class supports the same features as the synchronized block. What improvements are added?

A
  • Ability to request a lock without blocking
  • Ability to request a lock while blocking for a specified amound of time.
  • A lock can be created with a fairness property, in which the lock is granted to threads in the order it was requested.
53
Q

What is the CyclicBarrier class?

A

The CyclicBarrier class takes in its constructors a limit value, indicating the number of threads to wait for. As each thread finishes it calls the await() method on the cyclic barrier. Once the specified number of threads have each called await(), the barrier is released and all threads can continue.

54
Q

given the following method, add the use of CyclicBarrier such that all threads wait after removing all lions.

performTasks() {
removeLions();
cleanPen();
}

A

performTasks(CyclicBarrier c) {
try {
removeLions();
c.await();
cleanPen();
} catch(InterruptedException | BrokenBarrierException) { }
}

55
Q

What is the purpose of concurrent collection classes?

example: ConcurrentHashMap

A

to solve common memory consistency errors. A memory consistency error occurs when two threads have inconsistent views of what should be the same data.

56
Q

Why is the following code problematic? And how do we solve it?

var foodData = new HashMap();
foodData.put(“penguin”, 1);
foodData.put(“flamingo”, 2);
for (String key : foodData.keySet()){
foodData.remove(key);
}

A

This code will throw a ConcurrentModificationException during the second iteration of the loop, since the iterator on keySet() is not properly updated after the first element is removed.

Changing the first line to ConcurrentHashMap() will prevent the code from throwing an exception at runtime.

57
Q

When should you use concurrent collection classes?

A

Anytime that you are going to have multiple threads modify a collections object outside a synchronized block or method (even if you don’t expect a concurrency problem).

58
Q

What is the difference between a Queue and a BlockingQueue?

A

The BlockingQueue is a regular Queue that includes methods that will wait a specific amount of time to complete an operation.

59
Q

What is a LinkedBlockingQueue?

A

A LinkedBlockingQueue is an implementation of the BlockingQueue interface, which maintains a linked list between its elements.

60
Q

How can you obtain a synchronized collection if you’re not working with a concurrent collection class (such as ConcurrentHashMap)?

A

The Concurreny API includes methods for obtaining synchronized versions of existing nonconcurrent collection objects. These are defined in the Collections class.

example:

  • synchronizedCollection(Collection c)
  • synchronizedList(List list)
  • synchronizedSet(Set s)
61
Q

Does the following code produce an exception?

var foodData = new HashMap();
foodData.put(“penguin”, 1);
foodData.put(“flamingo”, 2);
var synFoodData = Collections.synchronizedMap(foodData);
for (String key : synFoodData.keySet()){
foodData.remove(key);
}

A

Yes. This will still throw a ConcurrentModificationException, despite using a synchronized version of foodData.

Other than iterating over the collection, the object returned by Collections.synchronized…() are safe from memory consistency errors and can be used among multiple threads.

62
Q

What types of liveness issues exist?

A
  • deadlock
  • starvation
  • livelock
63
Q

What is deadlock?

A

Deadlock occurs when two or more threads are blocked forever, each waiting on the other.

64
Q

What is starvation?

A

Starvation occurs when a single thread is perpetually denied access to a shared resource or lock. The thread is still active but unable to complete its work as a result of other threads constantly taking the resource that they are trying to access.

65
Q

What is livelock?

A

Livelock occurs when two or more threads are conceptually blocked forever, although they are each still active and trying to complete their task.

66
Q

What are two ways to create a parallel stream?

A
  • calling parallel() on an existing stream.
  • calling parallelStream() on a Collection Object.
67
Q

Will the following code compile?

public static void main(String[] args) {
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(2);
var manager = new LionPenManager();
var c1 = new CyclicBarrier(4);
var c2 = new CyclicBarrier (4, () ->
System.out.println(“*** Pen Cleaned!”));
for (int i= 0; 14; i++) {
service.submit(() -> manager.performTask(c1, c2));
} finally {
if (service 1= null) {
service.shutdown();
}
}
}

A

Yes, but this will result in a deadlock because the number of threads will never reach the cyclicBarrier required number (4) to continue execution

68
Q

Given an instance of a Stream s and a Collection c, which are valid ways of creating a parallel stream? (Choose all that apply.)

A. new ParallelStream(s)
B. c.parallel()
C. s.parallelStream()
D. c.parallelStream()
E. new ParallelStream(c)
F. s.parallel()

A

D, F

69
Q

Which of the following statements about the Callable call() and Runnable run() methods are correct? (Choose all that apply.)

A. Both can throw unchecked exceptions.
B. Callable takes a generic method argument.
C. Callable can throw a checked exception.
D. Both can be implemented with lambda expressions.
E. Runnable returns a generic type.
F. Callable returns a generic type.
G. Both methods return void.

A

A, C, D, F.

All methods are capable of throwing unchecked exceptions, so option A is correct. Runnable and Callable statements both do not take any arguments, so option B is incorrect. Only Callable is capable of throwing checked exceptions, so option C is also correct. Both Runnable and Callable are functional interfaces that can be implemented with a lambda expression, so option D is also correct. Finally, Runnable returns void and Callable returns a generic type, making option F correct and making options E and G incorrect.