Chapter 18: 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 system thread?

A

A system thread is created by the JVM and runs in the background of the application.

For example: the garbage collection is managed by a system thread that is created by the JVM and runs in the background, helping to free memory that is no longer in use.

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

What is a user-defined thread?

A

A user-defined thread is one created by the application developer to accomplish a specific task.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
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
5
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
6
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
7
Q

Is Runnable a functional interface?

A

yes

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

What is the method signature of the interface Runnable?

A

run()

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

Does the following code compile?

Runnable sloth = () -> {return;}

A

The Runnable interface has one abstract method: run(), which takes no arguments and returns void. Therefore, this code is valid.

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

Does the following code compile?

Runnable sloth = () -> 5;

A

No. It returns 5 while a Runnable cannot return a value.

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

Does the following code compile?

Runnable sloth = () -> System.out.println(“Hello World”);

A

Yes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
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
13
Q

Is order of thread execution guaranteed?

A

Order of thread execution is never guaranteed. It may be executed immediately or delayed for a significant amount of time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
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
15
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
16
Q

What is polling?

A

Polling is the process of intermittently checking data at some fixed interval.

Example: checking to see if a counter variable has reached 100 in a while loop, while another thread is incrementing it.

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

What exception can Thread.sleep() throw?

A

InterruptedException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
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
19
Q

Is order of thread execution with a single-thread executor guaranteed?

A

Yes, because it can only perform 1 task at a time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
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
21
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
22
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
23
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
24
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
25
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
26
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
27
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
28
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
29
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
30
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
31
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
32
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
33
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
34
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
35
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
36
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.

37
Q

Is Callable a functional interface?

A

Yes.

38
Q

What package does the Callable interface reside in?

A

java.util.concurrent

39
Q

What is the method signature of the interface Callable?

A

call()

40
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.
41
Q

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

A

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

42
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()

43
Q

What does the method awaitTermination return?

A

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

44
Q

invokeAll() and invokeAny() are synchronized/asynchonized

A

synchonized.

Meaning the JVM will wait until the results are available before returning control to the enclosing program.

45
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’.

46
Q

What do the invokeAll() and invokeAny() methods take as a parameter?

A

A collection of tasks.

47
Q

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

A

ScheduledExecutorService

48
Q

How can we create a new ScheduledExecutorService?

ScheduledExecutorService service = …

A

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

49
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.
50
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);

51
Q

What is the difference between scheduleAtFixedRate() and scheduleWithFixedDelay()

A

scheduleAtFixedRate() will run tasks repeatedly at specific intervals, without waiting for the previous task to finish. example -> A task need to run every 2 minutes.

scheduleWithFixedDelay() will wait for the previous task to be completed and wait an amount of time after that before repeating the execution. example -> A task need to run 2 minutes after completing the previous task.

52
Q

What is a thread pool?

A

A thread pool is a group of pre-instantiated reusable threads that are available to perform a set of arbitrary tasks.

53
Q

Which ExecutorService implementations use a thread pool?

A
  • CachedThreadPool
  • FixedThreadPool
  • ScheduledThreadPool
54
Q

What is the ExecutorService: CachedThreadPool?

A

An ExecutorService that creates a thread pool that creates new threads as needed but will reuse previously constructed threads when they are available.

55
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.

56
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.

57
Q

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

A

ExecutorService service = Executors.newFixedThreadPool(1);

1 thread = same as SingleThreadExecutor.

58
Q

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

A

Runtime.getRuntime().availableProcessors()

59
Q

What is a race condition?

A

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

60
Q

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

A
  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
61
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);

62
Q

What is mutual exclusion?

A

the property that at most one thread is executing a particular segment of code at a given time.

63
Q

What does the synchronized block do?

A

Each thread that arrives at the code block will first check if any threads are in the block. Only one thread can acquire the lock and execute the code block at a time.

64
Q

Given the following code, how can we ensure that the tasks will execute in order? (1 thread at a time).

...
private void incrementAndReport() {
   System.out.println((++sheepCount)+ "");
}
...
// using fixed thread pool with 20 threads.
for(int i = 0; i < 10; i++) {
    service.submit(() -> manager.incrementAndReport());
}
A
private void incrementAndReport() {
    synchronized(this) {
        System.out.println((++sheepCount)+ "");
    }
}

or

private synchronized void incrementAndReport() {
System.out.println((++sheepCount)+ “”);
}

65
Q

What Java types can be used in a synchronized statement?

A

Any Object

66
Q

Would the following code work in a thread-safe manner?

...
private Object someObj = new Object();
private void incrementAndReport() {
    synchronized(someObj) {
        System.out.println((++sheepCount)+ "");
    }
}
...
A

yes. We can synchronize on any object, as long as it is the same object.

67
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”);
}

68
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();
}
69
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().

70
Q

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

A

It will throw an IllegalMonitorStateException.

71
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.
72
Q

What is the problem with the following code?

Lock lock = new ReentrantLock();
if(lock.tryLock()) {
    try {
        lock.lock();
    } finally {
        lock.unlock();
    }
}
A

The thread obtains the lock twice but releases it only once. That means no new thread would be able to acquire the lock until the second one has been unlocked too.

73
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.
74
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.

75
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)    { }
}
76
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.

77
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.

78
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).

79
Q

What type of objects can be accessed by multiple threads without ever having a concurrency problem?

A

immutable or read-only objects.

80
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.

81
Q

What is a LinkedBlockingQueue?

A

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

82
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)
83
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.

84
Q

What is liveness?

A

Liveness is the ability of an application to be able to execute in a timely manner.

85
Q

What types of liveness issues exist?

A
  • deadlock
  • starvation
  • livelock
86
Q

What is deadlock?

A

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

87
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.

88
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.

89
Q

What are two ways to create a parallel stream?

A
  • calling parallel() on an existing stream.

- calling parallelStream() on a Collection Object.