Concurrency Flashcards

1
Q

what is a thread?

A

smallest unit of execution that can be scheduled by the OS

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

what is a process?

A

group of associated threads that execute in the same shared memorythreads can communicate with each other

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

what is a task?

A

single unit of work performed by a thread

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

can a thread perform multiple tasks?

A

yes, but only one task at a time

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

what is a system thread?

A

a thread that is created by the JVM

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

what is a user-defined thread?

A

a thread created by a developer

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

are all java programs multi-threaded?

A

yes, technically always system threads running in the background even if application only requires a single thread

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

what is a single-threaded application referring to?

A

a single user-defined thread(any number of system threads)

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

what is a daemon thread?

A

a thread that will not prevent the JVM from exiting once the program finishesex: system thread for garbage collection. when program finishes, if gb coll thread is the only one running, JVM can shut down.

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

what types of threads can be marked as daemon threads?

A

system threads user-defined threads

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

what is 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
12
Q

how does the JVM determine which threads will execute given the CPUs?

A

often, more threads than available CPUs, so threads must be scheduled.

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

what is a context switch?

A

when threads are being executed, they may only be allotted a limited number of CPU cycles. if the thread doesn’t finish executing, the thread’s state must be stored and later restored to continue processing. performance cost with storing/restoring

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

what is thread priority?

A

a thread can interrupt or supercede another thread if it has a higher thread priority

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

what are the defaults = to? Thread.MIN_PRIORITY Thread.NORM_PRIORITY Thread.MAX_PRIORITY

A

1510

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

how is it determined which thread runs first if both have same priority?

A

thread scheduler will arbitrarily decide

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

what is Runnable?

A

a functional interface that takes no arguments and returns no data@FunctionalInterfacepublic interface Runnable() { void run();}

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

what is Runnable commonly used for?

A

define work a thread will do separate from the main application thread

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

What is the Thread class commonly used for?

A

executing a thread similar to Runnable

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

What is the 2-step process from executing a thread?

A

define the task in run();start the thread - Thread.start();

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

what are two ways to define the task a thread will do?

A

1) pass a Runnable object or lambda to Thread constructor2) extend Thread class and override run method

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

when Thread.start() is not used, what order are threads run in?

A

run tasks are completed on the main app thread in the order of code by line

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

when Thread.start() is used, what order are threads run in?

A

indeterminate - threads are run in parallel to the main app thread

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

when is extending Thread preferable to implementing Runnable?

A

you need thread priorities set

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
when is implementing Runnable preferable to extending Thread?
need to extend another classbetter oo design - separates task from object (Thread) performing itallows class to be used by numerous Concurrency API classes
26
what can you now use to perform thread tasks instead of creating Thread objects directly?
ExecutorService
27
what does Thread.sleep() do?
puts to sleep the main app thread
28
what exception does Thread.sleep() throw?
InterruptedException - checked!
29
what does the ExecutorService provide?
thread poolingthread scheduling
30
how do you use the ExecutorService?
obtain an instance of ExecutorServicesend tasks to be processed
31
what is the benefit of using a Executors.newSingleThreadExectuor() for a small number of threads?
it provides an instance of ExecutorService that ensures all tasks sent to it are run on a single thread (separate from main application thread), and run in order they are sent to the Servicethis ordering guarantee disappears with larger number of threadsdo not rely on it
32
since thread executor creates a non-daemon thread, what must be done for every one?
ThreadExectuor.shutdown() must be called to terminate the thread
33
what happens when shutdown() is called on a thread executor?
1) new tasks submitted are rejected - RejectedExecutionException is thrown2) all previously submitted tasks are completed
34
does shutdown() stop any tasks from running?
no
35
how would you attempt to stop tasks immediately?
shutdownNow() attempts to stop any currently running tasks & discard any previously submitted but not yet started tasks - returns List of tasks submitted but never run
36
can you use ExecutorService with try-with-resources?
no, it doesn't implement AutoCloseable
37
how would you shutdown a thread executor if it's shared across the lifetime of the application?
create static method to shutdown thread whenever program is going to exit
38
what are the ways to submit a task to an ExecutorService?
void execute(Runnable task) - fire and forgetFuture> submit(Runnable task) - returns a Future representing task Future submit(Callable task) - returns a Future w/ pending result of task List> invokeAll(Collection extends Callable> task) throws InterruptedException- executes tasks synchronously (tasks need to complete before main thread can resume)- returns a list of Futures in order tasks were submitted in collection T invokeAny(Collection extends Callable> task) throws InterruptedException, ExecutionException- executes tasks synchronously (tasks need to complete before main thread can resume)- returns one Futures of completed task, - cancels any unfinished tasks
39
how long will invokeAll() method wait vs. invokeAny()?
invokeAll() will wait indefinitely for all tasks to completeinvokeAny() will wait indefinitely for a single task to complete - remember first task completed isn't necessarily task guaranteed to be returned
40
can you set a timeout value for invokeAll() and invokeAny()?
yes, overloaded methods to allow this
41
what Future method is used to determine if a task completed, threw an exception, or was canceled?
boolean isDone()
42
what Future method is used to determine if a task was cancelled before it completed normally?
boolean isCancelled()
43
what Future method is used to attempt to cancel a task
boolean cancel()
44
what Future methods are used to retrieve result of task?
V get()V get(long timeout, TimeUnit unit)
45
what happens if a Future result isn't returned within the timeout specified?
TimeoutException is thrown
46
if a Runnable instance is used in ExecutorService.submit(Runnable task), what type is returned?
method returns Future - V is a generic that matches the return type of Runnable's functional interface method. run() is void - therefore nothing is returned with Runnable is used for submit()
47
What are the 7 TimeUnit constants used for the Concurrency API methods?
TimeUnit.NANOSECONDSTimeUnit.MICROSECONDSTimeUnit.MILLISECONDSTimeUnit.SECONDSTimeUnit.MINUTESTimeUnit.HOURSTimeUnit.DAYS
48
What is the Callable interface?
@FunctionalInterfacepublic interface Callable() {V call() throws Exception;}
49
what's the difference between Runnable & Callable?
Runnable- run() method cannot throw exception- run() method has void return type - Future always returns nullCallable- call() method can throw CheckedException- call() method can return any type - Future can return null or any type
50
what is the main benefit of Callable over Runnable?
Callable returns a result so details can be retrieved from task
51
What is the main benefit of Callable over Supplier?
Callable can throw an exception
52
What is an ambiguous lambda expression?
a lambda expression such that the compiler cannot determine which method it should be passed toex:use(Supplier task)use(Callable task)use(() -> {throw new IOException();});// remember parentheses needed around body + semicolon needed
53
use(Supplier task) use(Callable task) use(() -> {throw new IOException();}); what happens when this compiles and runs?
trick! doesn't compile. compiler doesn't take into account that Callable can throw an exception and Supplier cannot. since it can't determine what to do, it creates a compiler error
54
use(Supplier task) use(Callable task) use(() -> {throw new IOException();}); How can we solve this?
Cast the lambda expression to one of the explicit types. since the code throws an exception, must use Callable version for code to compileuse((Callable) () -> {throw new IOException();});
55
when are Callable and Runnable interchangeable?
when the lambda expression doesn't throw an exception and doesn't return anything
56
will these compile? submit(() -> {Thread.sleep(); return null;}); submit(() -> {Thread.sleep();});
first one treats lambda as Callable since there is a return- Thread.sleep() throws an exception and Callable supports that- compilessecond one treats lambda as a Runnable since there is no return- Thread.sleep() throws an exception and Runnable does not support that- does not compile
57
what method can you use to wait for a set of submitted tasks to complete once you've run shutdown()?
since you have run shutdown(), the thread no longer accepts new tasks and is attempting to finish task submitted previous to the shutdown() callawaitTermination(long timeout, TimeUnit unit);- awaits specified time- returns sooner if tasks finish or an InterruptedException is thrownisTerminated();- check if thread is terminated
58
What ExecutorService instance would you use to get a thread executor that will execute on a schedule?
ScheduledThreadServiceExecutorService.newSingleThreadScheduledExecutor();
59
what are the 4 methods for ScheduledThreadService
schedule(Runnable task)schedule(Callable task)scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)- creates task after initial delay- creates new task every period that passes specified by period unitscheduleAtFixedDelay(Runnable task, long initialDelay, long period, TimeUnit unit)- creates task after initial delay- creates new task every period that passes specified by period unit AFTER previous task has completed
60
are scheduled tasks guaranteed to be run with a scheduled delay?
no - if thread is shutdown by the time the thread execution time is reached, the task will be discarded- if there are no available threads, the task will wait in a queue
61
do scheduled thread executor tasks return anything?
no, since they are scheduled to run infinitely until thread stops, they would generate endless objectsscheduled thread executor methods take Runnable parameters
62
what is the main difference between scheduleAtFixedDelay and scheduleAtFixedRate?
SAFD waits for current task to finishSAFR generates new tasks regardless of previous task status
63
what are the 3 executor services that act on a pool of threads?
newCachedThreadPool()newFixedThreadPool()newScheduledThreadPool()
64
how does newCachedThreadPool() work?
creates thread pool that creates threads as needed, uses existing threads when availablecreates a ExecutorService
65
how does newFixedThreadPool() work?
creates a thread pool that reuses a FIXED number of threads with an unbounded shared queuecreates a ExecutorService
66
how does newScheduledThreadPool() work?
creates a thread pool that can schedule commands to run after a given delay or execute periodicallycreates a ScheduledExecutorService
67
what is a cachedThreadPool good for? bad for?
many short-lived asynchronous taskslong-lived tasks - the pool size will grow rather large over the lifecycle of the application
68
how can a newFixedThreadPool be like a newSingleThreadExecutor?
create newFixedThreadPool with a value of 1 thread
69
what is the benefit of a newScheduledThreadPool over a newSingleThreadExecutor when using scheduleAtFixedRate()?
with a pool, if the number of threads in the pool is large enough, as tasks finish, they can be returned to the pool to execute at the fixed rate, keeping the pool a pre-determined size.with the single thread, a new task will be scheduled indefinitely.
70
when is it generally safe to create a large thread pool?
when a thread task depends on waiting for an external resource - DB, network, etc.since most of the time is spent waiting and task isn't CPU intensive, safe to have a large pool
71
what is thread safety?
property of an object that guarantees safe execution by multiple threads at the same time
72
what is a race condition?
unexpected result of two tasks executing at the same time
73
what does it mean for something to be atomic?
property of operation to be carried out as a single unit of execution that cannot be interrupted by a thread
74
what package has classes that coordinate access to primitive variables and object references?
java.util.concurrentAtomicBooleanAtomicIntegerAtomicIntegerArrayAtomicLongAtomicLongArrayAtomicReferenceAtomicReferenceArray
75
what methods are available on atomic primitives and object references?
get() - returns valueset() - sets given valuegetAndSet() - return old value, set new valueincrementAndGet() - increase value, get new valuegetAndIncrement() - get old value, increase new valuedecrementAndGet() - decrease value, get new valuegetAnddecrement() - get old value, decrease new value
76
does an Atomic primitive or object guarantee order in thread execution?
no, thread execution is not affected. ensures data consistency between threads.
77
what is a lock or monitor used for?
it locks a synchronized code block so only one thread can execute a given block at a time.thread acquires lockthread executesthread gives up lockone of waiting threads acquires lock
78
what can be synchronized?
any object
79
when synchronizing threads, what part of the task do we want to make sure we synchronize?
the execution of the task, NOT the creation of the task
80
should Atomic variables be used inside synchronized blocks?
technically legalno thread safety improvements since code block is already thread safe
81
what are two ways to synchronize a non-static method?
//synchronized keyword after access modifier in method declarationpublic synchronized void aMethod()// synchronized keyword on object inside methodpublic void aMethod() { synchronized (this) { }}
82
what are two ways to synchronize a static method?
//synchronized keyword after access modifier in method declarationpublic static synchronized void aMethod()// synchronized keyword on the class object inside methodpublic static void aMethod() { synchronized (TheClassName.class) { }}
83
when would you want to synchronize a static method?
manage thread access across all instances of a class
84
what is the cost of synchronization?
possible performance hits to protect data integrity
85
what is the purpose of concurrent collections?
help manage concurrent access to collections (very common problem) with performance benefits where synchronization isn't neededcould technically implement with synchronized keyword, but prone to implementation mistakes
86
how can a ConcurrentModificationException occur with a single thread on a regular collection?
when iterating over a collection and updating the collection and the iterator over the collection isn't updated, a ConcurrentModificationException will occur
87
how can you prevent a ConcurrentModificationException that could occur with a single thread?
use a Concurrent version of the collectionmap ConcurrentHashMapmap.keyset() - produces an iterator that updates every time the map is updated
88
what is a memory consistency error?
when two threads have different views of the same data
89
what does it mean for a collection to be blocking?
the thread access the collection will wait a certain amount of time before completing an operation
90
what does BlockingQueue.offer(E e, long timeout, TimeUnit unit) do?
offers up an element E to queue waiting the specified amount of timereturns false if no space available after time waited
91
what does BlockingQueue.poll(E e, long timeout, TimeUnit unit) do?
polls for an element E and removes it from the queue, waiting the specified amount of timereturns false if null if no object available after time waited
92
how are the blocking deque methods similar to the blocking queue methods?
same except offerFirstofferLastpollFirstpollLast
93
can blocking collections use non-blocking methods?
yes, they implement regular collections so they can use those methods
94
what do all blocking methods have in common?
throw checked exception Interrupted exception
95
What are the concurrent versions of TreeSet and TreeMap?
ConcurrentSkipListSetConcurrentSkipListMap
96
How do the CopyOnWrite collections behave when 1) content of object changes 2) element reference changes
1) nothing2) copies entire collection to a new collection object
97
what happens to iterators that reference a CopyOnWrite collection when those collections are modified?
if the iterator existed before the modification, the iterator will still reference the collection prior to modification- add 3 items to collection- iterate over collection and print each item, also add a new item each time- will print the original 3 items- size will be 6 at the end
98
when are CopyOnWrite collections most often used?
high read, low writetoo many writes = lots of memory allocated to updated collection objects
99
synchronized collection vs. concurrent collection?
both provide synchronization on access to elements (get and set) synchronized collection does not synchronize iterators created from collection - will throw a ConcurrentModificationException concurrent collection does synchronize on iterators - will not throw an exception
100
what is a serial stream?
a stream where the results are ordered, with only one entry processed at at time
101
what is a parallel stream?
a stream that processes results concurrently, using multiple threads
102
how can the stream map() method benefit from parallel streams?
parallel streams can process elements so map() method can complete more quickly
103
what are 2 ways to create parallel streams?
parallel() - performed on a stream objectArrays.asList(1, 2, 3).stream().parallel();parallelStream()- performed any collectionArrays.asList(1, 2, 3).parallelStream();
104
what type of operation is parallel()?
intermediate operation
105
what is the difference in results between the two: Arrays.asList(1, 2, 3, 4, 5).stream().forEach(s -> System.out.println(s)); Arrays.asList(1, 2, 3, 4, 5).parallelStream().forEach(s -> System.out.println(s));
12345indeterminate order - like several Runnable lambdas submitted to a pooled thread executor
106
how can you force a parallel stream to still print each stream element in order?
Arrays.asList(1, 2, 3, 4, 5).parallelStream().forEachOrdered(s -> System.out.println(s));lose performance benefits of parallel stream
107
why use forEachOrdered on a parallel stream if it takes away performance benefits?
other stream intermediary operations can still benefit from parallel streams
108
what size data sets are best for parallel streams?
large data setsparallel streams have some overhead - only worth it for large data setsminimal improvements for small sets
109
what is a stateless/stateful lambda expression?
stateless - lambda that doesn't depend on any state that might change during execution of pipelinestateful - opposite of stateless
110
what is the result of stateful operations in a stream?
unpredictable ordering/side effects on processing
111
what type of collection should always be used when working with parallel streams?
concurrent collections
112
what happens if you use a non-concurrent collection with parallel streams?
unpredictable results - you could have 2 threads updating the same collectionif you are adding elements to the list, periodically the array backing the list needs to be expanded and if two threads create a new array at the same time, a result could be lost
113
what is the issue with using parallel streams with reductions based on order? findAny()
parallel threads will process and first thread to finish will return result - unpredictable results
114
how will the results differ for ordered operations on a parallel vs serial stream?
results will be the sameparallel stream may run more slowly due to the synchronizing of threads required
115
what does stream().unordered() produce?
an unordered stream beneficial for performance when running parallel streams
116
what are the 3 rules for reduce()/collect() arguments to guarantee order of results for parallel streams?
combiner.apply(idenitity, u) is equal to uaccumulator must be associative and stateless(a op b) op c = a op (b op c)combiner must be associative and stateless
117
why should you use the 3-argument version of reduce() for parallel streams?
having an explicit combiner will allow the JVM to partition operations more efficiently
118
when using a ConcurrentSkipListSet or ConccurentSkipListMap - what order will results be returned?
natural ordering
119
what are 3 rules that guarantee collect() will run EFFICIENTLY ?
stream is parallelCollector used has1) Collector.Characteristic.CONCURRENT2) Collector.Characteristic.UNORDERED or stream is unordered
120
what are the two Collectors available that are both CONCURRENT and UNORDERED?
Collectors.toConcurrentMap()Collectors.groupingByConcurrent()
121
What are CyclicBarrier and ForJoinPool used for generally?
to coordinate tasks among a group of related threads
122
how does a CyclicBarrier coordinate threads?
number of threads to wait for is passed to CyclicBarrier constructorcyclicBarrier.await() is called for each thread between tasks- threads will wait until the number of threads to wait for is reached and each has called await()- all threads can continue
123
can you reuse a CyclicBarrier?
no - once the await() method has been used to wait for the specified number of threads - need new barrier for coordination
124
"what does new CyclicBarrier(4, () -> System.out.println(""done!"") do? CyclicBarrier(int, Runnable)"
"creates a cyclic barrier for 4 threads - once 4 threads have reached the await() method - ""done!"" will be printed"
125
what are 2 ways to use a CyclicBarrier?
create static objectpass to thread
126
what happens if your thread pool is smaller than the thread limit set in a Cyclic Barrier used on the thread pool?
deadlockCyclicBarrier will wait forever since number of threads available < thread limit for cyclic barrier
127
why would cyclic barrier cause a loss to performance?
all threads can only move past the barrier(s) as fast as the slowest thread
128
what is the ForkJoinPool used for?
based on recursionsplit complicated tasks into multiple tasks based on need
129
what are the 3 steps to applying the fork/join framework?
1) create a ForkJoinTask (extend RecursiveAction or Recursive Task)2) Create the ForkJoinPool3) Start the ForkJoinTaskForkJoinTask> task = new RecursiveActionClass();ForJoinPool pool = new ForkJoinPool();pool.invoke(task);
130
RecursiveAction vs. RecursiveTask?
both abstract classes with compute() methodcompute() method contains recursive methodRecursiveAction like Runnable - voidRecursiveTask like Callable - returns type T
131
when using a RecursiveAction - what method is used to call itself?
void invoke(RecursiveAction)void invokeAll(RecursiveAction)
132
when using a RecursiveTask - what methods are used to call itself?
fork()- create a new RecursiveTask - recursiveTask.fork() will tell the task to run on a separate threadjoin()- recursiveTask.join() will tell the current thread to wait for the forked thread to complete
133
what order must fork() and join() be called on the separated thread in order for tasks to be done in parallel?
before main thread subtask begins, call fork() on secondary taskafter main thread finishes retrieving results, call join() on secondary task
134
What is liveness?
ability of app to be able to execute in a timely manner
135
what are the 3 liveness issues to know?
deadlockstarvation livelockcauses of hung threads
136
what is deadlock?
deadlock occurs when two+ threads are blocked forever - each waiting on the other
137
what is one common way to avoid deadlocks?
make sure all threads order their resource requests so if one thread begins on a sequence, the other thread waits until the first finishes so resources are available
138
what is starvation?
starvation occurs when a single thread is perpetually denied access to a shared resource or lockthread is active, but unable to complete work
139
what is livelock?
livelock is when 2+ threads are conceptually blocked forever, but are still activeoften a resolution attempt when deadlock detectedthreads release all locked resources and attempt to regain locks againoften times this just reproduces the same deadlock over and over
140
what is a race condition?
when two tasks should be completed sequentially are completed concurrently