Concurrency Flashcards
what is a thread?
smallest unit of execution that can be scheduled by the OS
what is a process?
group of associated threads that execute in the same shared memorythreads can communicate with each other
what is a task?
single unit of work performed by a thread
can a thread perform multiple tasks?
yes, but only one task at a time
what is a system thread?
a thread that is created by the JVM
what is a user-defined thread?
a thread created by a developer
are all java programs multi-threaded?
yes, technically always system threads running in the background even if application only requires a single thread
what is a single-threaded application referring to?
a single user-defined thread(any number of system threads)
what is a daemon thread?
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.
what types of threads can be marked as daemon threads?
system threads user-defined threads
what is concurrency?
the property of executing multiple threads and processes at the same time?
how does the JVM determine which threads will execute given the CPUs?
often, more threads than available CPUs, so threads must be scheduled.
what is a context switch?
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
what is thread priority?
a thread can interrupt or supercede another thread if it has a higher thread priority
what are the defaults = to? Thread.MIN_PRIORITY Thread.NORM_PRIORITY Thread.MAX_PRIORITY
1510
how is it determined which thread runs first if both have same priority?
thread scheduler will arbitrarily decide
what is Runnable?
a functional interface that takes no arguments and returns no data@FunctionalInterfacepublic interface Runnable() { void run();}
what is Runnable commonly used for?
define work a thread will do separate from the main application thread
What is the Thread class commonly used for?
executing a thread similar to Runnable
What is the 2-step process from executing a thread?
define the task in run();start the thread - Thread.start();
what are two ways to define the task a thread will do?
1) pass a Runnable object or lambda to Thread constructor2) extend Thread class and override run method
when Thread.start() is not used, what order are threads run in?
run tasks are completed on the main app thread in the order of code by line
when Thread.start() is used, what order are threads run in?
indeterminate - threads are run in parallel to the main app thread
when is extending Thread preferable to implementing Runnable?
you need thread priorities set
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
what can you now use to perform thread tasks instead of creating Thread objects directly?
ExecutorService
what does Thread.sleep() do?
puts to sleep the main app thread
what exception does Thread.sleep() throw?
InterruptedException - checked!
what does the ExecutorService provide?
thread poolingthread scheduling
how do you use the ExecutorService?
obtain an instance of ExecutorServicesend tasks to be processed
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
since thread executor creates a non-daemon thread, what must be done for every one?
ThreadExectuor.shutdown() must be called to terminate the thread
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
does shutdown() stop any tasks from running?
no
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
can you use ExecutorService with try-with-resources?
no, it doesn’t implement AutoCloseable
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
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
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
can you set a timeout value for invokeAll() and invokeAny()?
yes, overloaded methods to allow this
what Future method is used to determine if a task completed, threw an exception, or was canceled?
boolean isDone()
what Future method is used to determine if a task was cancelled before it completed normally?
boolean isCancelled()
what Future method is used to attempt to cancel a task
boolean cancel()
what Future methods are used to retrieve result of task?
V get()V get(long timeout, TimeUnit unit)
what happens if a Future result isn’t returned within the timeout specified?
TimeoutException is thrown
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()
What are the 7 TimeUnit constants used for the Concurrency API methods?
TimeUnit.NANOSECONDSTimeUnit.MICROSECONDSTimeUnit.MILLISECONDSTimeUnit.SECONDSTimeUnit.MINUTESTimeUnit.HOURSTimeUnit.DAYS
What is the Callable interface?
@FunctionalInterfacepublic interface Callable() {V call() throws Exception;}
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
what is the main benefit of Callable over Runnable?
Callable returns a result so details can be retrieved from task
What is the main benefit of Callable over Supplier?
Callable can throw an exception
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
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
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();});
when are Callable and Runnable interchangeable?
when the lambda expression doesn’t throw an exception and doesn’t return anything
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