Concurrency Flashcards

1
Q

thread

A

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

process

A

a group of associated threads that execute in the same, shared environment

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

Shared Environment

A

the threads in the same process share the same memory space and can communicate directly with one another

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

Concurrency

A

The property of executing multiple threads and processes at the same time

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

Context Switch

A

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
6
Q

thread priority

A

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

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

Values of

Thread.MIN_PRIORITY

Thread.NORM_PRIORITY

Thread.MAX_PRIORITY

A

1

5

10

Note: If two threads have the same priority, the thread scheduler will arbitrarily choose the one to process first in most situations.

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

Runnable

A

a functional interface that takes no arguments and returns no data.

commonly used to de ne the work a thread will execute, separate from the main application thread.

@FunctionalInterface public interface Runnable { void run();
}

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

How to execute a task with the Thread class

A

First you define the Thread with the corresponding task to be done. Then you start the task by using the Thread.start() method.

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

Two ways to define the task for a Thread instance

A

1) Provide a Runnable object or lambda expression to the Thread constructor (preferred method):

public class PrintData implements Runnable {
    public void run() {
        //print something
    }
    public static void main(String[] args) {
        (new Thread(new PrintData())).start();
    }
}

2) Create a class that extends Thread and overrides the run() method:

public class ReadInventoryThread extends Thread { 
    public void run() {
       System.out.println("Printing zoo inventory"); 
}
    public static void main(String[] args) {
        (new ReadInventoryThread()).start();
    } 
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What order are threads processed in?

A

Whatever the thread scheduler decides

There is no guarantee that the thread you start first will be processed before the second. They could be broken up over time switching between threads too. Shit’s nuts and unpredictable.

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

A reason to prefer extending Thread instead of implementing Runnable when creating your own thread

A

If you need to define your own Thread rules upon which multiple tasks will rely, such as a priority Thread, extending Thread may be preferable.

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

3 reasons to prefer implementing Runnable instead of extending Thread when creating your own thread

A

1) Implementing Runnable lets you extend another class.
2) Implementing Runnable is often a better object-oriented design practice since it separates the task being performed from the Thread object performing it.
3) Implementing Runnable allows the class to be used by numerous Concurrency API classes.

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

Polling

A

the process of intermittently checking data at some fixed interval

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

Thread.sleep(long mills)

A

Requests the current thread of execution rest for a speci ed number of milliseconds. When used inside the body of the main() method, the thread associated with the main() method will pause, while the separate thread will continue to run.

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

What exception might Thread.sleep() throw?

A

InterruptedException

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

ExecutorService

A

An interface that includes numerous useful features, such as thread pooling and scheduling, which would be cumbersome for you to implement in every project. Therefore, it is recommended that you use this framework anytime you need to create and execute a separate task, even if you need only a single thread.

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

How to create an instance of ExecutorService for a single thread and execute the thread. Then close the ExecutorService.

A
ExecutorService service = null; 
try {
   service =   
   Executors.newSingleThreadExecutor();
   service.execute(() ->   
   System.out.println("Running"));
}
finally {
   service.shutdown();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

If a single-thread ExecutorService instance is used to execute multiple threads, what order will they be executed in?

A

The order in which they are added to the ExecutorService

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

What will happen if you don’t call shutdown() on your executor?

A

Your application will never terminate.

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

RejectedExecutionException

A

Thrown when a new task is submitted to the thread executor while it is shutting down

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

isShutdown() and isTerminated()

A

isShutdown() will return true while an executor is being shut down and after it shuts down

isTerminated() will return false while an executor is being shut down and return true after it shuts down

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

Difference between shutdown() and shutdownNow()

A

shutdown() will finish executing any tasks that have already been submitted to the executor

shutdownNow() will attempt to cancel any currently running tasks or tasks that are queued up. Also returns a List of tasks that were submitted to the thread executor but that were never started.

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

void execute(Runnable command)

A

Executes a Runnable task at some point in the future

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

Future> submit(Runnable task)

A

Executes a Runnable task at some point in the future and returns a Future representing the task

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

Future submit(Callable task)

A

Executes a Callable task at some point in the future and returns a Future representing the pending results of the task

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

List> invokeAll( Collection extends Callable> tasks)

A

Executes the given tasks, synchronously returning the results of all tasks as a Collection of Future objects, in the same order they were in the original collection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q
T invokeAny(
Collection extends Callable> tasks)
A

Executes the given tasks, synchronously returning the result of one of finished tasks, cancelling any unfinished tasks

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

Which method is preferred, submit() or execute()?

A

submit()

Mostly just cuz they basically do the same thing but submit returns a Future object that can be used

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

Future method

boolean isDone()

A

Returns true if the task was completed, threw an exception, or was cancelled

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

Future method

boolean isCancelled()

A

Returns true if the task was cancelled before it completely normally.

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

Future method

boolean cancel()

A

Attempts to cancel execution of the task.

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

Future method

V get()

A

Retrieves the result of a task, waiting endlessly if it is not yet available.

34
Q

Future method

V get(long timeout, TimeUnit unit)

A

Retrieves the result of a task, waiting the specified amount of time. If the result is not ready by the time the timeout is reached, a checked TimeoutException will be thrown.

35
Q

Callable interface

A

similar to Runnable except that its call() method returns a value and can throw a checked exception.

@FunctionalInterface public interface Callable { 
    V call() throws Exception;
}
36
Q

ambiguous lambda expression

A

When the compiler is unable to assign a functional interface to a lambda expression

37
Q

awaitTermination(long timeout, TimeUnit unit)

A

Call this method on an ExecutorService object to wait a specified amount of time before continuing on, or it will return earlier if the tasks finish before the specified amount of time

38
Q

ScheduledExecutorService

A

A subinterface of ExecutorService that allows us to schedule a task for the future, possibly repeatedly if wanted.

39
Q

How to create an instance of ScheduledExecutorService for a single thread

A

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

40
Q

ScheduledExecutorService Method

schedule(Callable callable, long delay, TimeUnit unit)

A

Creates and executes a Callable task after the given delay

41
Q

ScheduledExecutorService Method

schedule(Runnable command, long delay, TimeUnit unit)

A

Creates and executes a Runnable task after the given delay

42
Q

ScheduledExecutorService Method

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

A

Creates and executes a Runnable task after the given initial delay, creating a new task every period value that passes.

43
Q

ScheduledExecutorService Method

scheduleAtFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)

A

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 com- mencement of the next

44
Q

thread pool

A

a group of pre-instantiated reusable threads that are available to perform a set of arbitrary tasks

45
Q

Executors method

newCachedThreadPool()

A

Creates a thread pool that creates new threads as needed, but will reuse previ- ously constructed threads when they are available.

Returns an ExecutorService object

46
Q

Executors method

newFixedThreadPool(int nThreads)

A

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.

Returns an ExecutorService object

47
Q

Executors method

newScheduledThreadPool(int nThreads)

A

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

Returns a ScheduleExecutorService object

48
Q

race condition

A

the unexpected result of two tasks executing at the same time

49
Q

Atomic

A

the property of an operation to be carried out as a single unit of execution without any interference by another thread

50
Q

What are the Atomic classes I need to know?

A

1) AtomicBoolean
2) AtomicInteger
3) AtomicIntegerArray
4) AtomicLong
5) AtomicLongArray
6) AtomicReference
7) AtomicReferenceArray

51
Q

Atomic methods

get()

set()

getAndSet()

incrementAndGet()

getAndIncrement()

decrementAndGet()

getAndDecrement()

A

get():
Retrieve the current value

set():
Set the given value, equivalent to the assignment = operator

getAndSet():
Atomically sets the new value and returns the old value

incrementAndGet():
For numeric classes, atomic pre-increment operation equivalent to ++value

getAndIncrement():
For numeric classes, atomic post-increment operation equivalent to value++

decrementAndGet():
For numeric classes, atomic pre-decrement operation equivalent to –value

getAndDecrement():
For numeric classes, atomic post-decrement operation equivalent to value–

52
Q

Synchronized Block

A

Notated by the synchronized keyword, they are used to make sure that the operations in the synchronized block will only be run by one thread at a time.

synchronized(this) {
   // Work to be completed by one thread at a   
       time 
}

Note: you can synchronize on any object

53
Q

synchronized method modifier

A

Does the same thing as if the entire method content were wrapped in a synchronized block

54
Q

BlockingQueue method

offer(E e, long timeout, TimeUnit unit)

A

Adds item to the queue waiting the specified time, returning false if time elapses before space is available

Throws InterruptedException if interrupted

55
Q

BlockingQueue method

poll(long timeout, TimeUnit unit)

A

Retrieves and removes an item from the queue, waiting the specified time, returning null if the time elapses before the item is available

Throws InterruptedException if interrupted

56
Q

LinkedBlockingQueue vs. LinkedBlockingDeque

A

LinkedBlockingDeque maintains a doubly-linked list and has offer and poll methods to deal with the first and last elements efficiently.

57
Q

ConcurrentSkipListSet and ConcurrentSkipListMap

A

Pretty much just concurrent versions of their TreeSet and TreeMap, respectively.
They maintain their elements or keys in the natural ordering of their elements.

58
Q

CopyOnWriteArrayList and CopyOnWriteArraySet

A

These classes copy all of their elements to a new underlying structure anytime an element is added, modi ed, or removed from the collection. Although the data is copied to a new underlying structure, our reference to the object does not change.

59
Q

What is the output here? Why?

List list = new CopyOnWriteArrayList<>(Arrays.asList(4,3,52)); for(Integer item: list) {
System.out.print(item+” “);
list.add(9); }
System.out.println(); System.out.println(“Size: “+list.size());

A

4 3 52
Size: 6

With CopyOnWrite collections, any iterator established prior to a modification will not see the changes, but instead it will iterate over the original elements prior to the modification.

60
Q

How to obtain a synchronized collection from a regular collection

A

The Concurrency API provides methods for converting Lists/Maps/Sets/Collections using something like

List list = new ArrayList<>(Arrays.asList(3,4,5));
list = Collections.synchronizedList(list)

61
Q

What is the thing to watch for when using the synchronized collections?

A

They do not synchronize access on any iterators that you may create from the synchronized collection. Therefore, it is imperative that you use a synchronization block if you need to iterate over any of the synchronized collections

62
Q

parallel stream

A

a stream that is capable of processing results concurrently, using multiple threads.

63
Q

How to create a parallel stream from an existing stream

A

Use the parallel() intermediate operation

Stream stream = Arrays.asList(1,2,3,4,5,6).stream(); Stream parallelStream = stream.parallel();

64
Q

How to create a parallel stream from a collection

A

Use the parallelStream() operation

Stream parallelStream2 = Arrays.asList(1,2,3,4,5,6).parallelStream();

65
Q

stateful lambda expression

A

One whose result depends on any state that might change dur- ing the execution of a pipeline.

Avoid these in parallel streams

66
Q

3 Requirements for Parallel Reduction with collect()

A

1) The stream is parallel.
2) The parameter of the collect operation has the Collector.Characteristics.CONCURRENT characteristic.
3) Either the stream is unordered, or the collector has the characteristic Collector.Characteristics.UNORDERED.

67
Q

3 Requirements for reduce() arguments on parallel streams

A

1) The identity must be defined such that for all elements in the stream u, combiner.apply(identity, u) is equal to u.
2) The accumulator operator op must be associative and stateless such that (a op b) op c is equal to a op (b op c).
3) The combiner operator must also be associative and stateless and compatible with the identity, such that for all u and t combiner.apply(u,accumulator.apply(identity,t)) is equal to accumulator.apply(u,t).

68
Q

What are the two Collectors methods that produce an unordered and concurrent collection

A

Collectors.toConcurrentMap

Collectors.groupingByConcurrent

69
Q

CyclicBarrier

A

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.

70
Q

How many times can you use a CyclicBarrier object?

A

As many times as you need

If its limit is 5 and you need to work with 15 threads for example, you can use the same CyclicBarrier object three times.

71
Q

What are the two classes you can extend to implement a fork/join solution?

A

RecursiveAction and RecursiveTask

both of which implement the ForkJoinTask interface

72
Q

What method must you implement for RecursiveAction and RecursiveTask?

A

void compute() for RecursiveAction

T compute() for RecursiveTask

73
Q

Once you define your task class for the fork/join solution, how do you start it?

(assume the task class is called Weigh)

A
ForkJoinTask> task = new Weigh(); ForkJoinPool pool = new ForkJoinPool();
pool.invoke(task);
74
Q

invokeAll method

A

takes two instances of the fork/join class and does not return a result.

75
Q

fork() method

A

causes a new task to be submitted to the pool and is similar to the thread executor submit() method.

76
Q

join() method

A

called after the fork() method and causes the current thread to wait for the results of a subtask.

77
Q

In what order should you call the methods for the fork/join framework?

A

fork()
compute()
join()

78
Q

Deadlock

A

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

79
Q

Starvation

A

when a single thread is perpetually denied access to a shared resource or lock.

80
Q

Livelock

A

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