Concurrency: Foundation & Executor Framework Flashcards
What are the 2 ways of implementing a thread?
- Extend the Thread class and overwrite the run() method
2. Implement the Runnable interface in a separate or anonymous class
Which method should we use to execute the run() method of a thread?
the start() method
What’s the purpose of the join() method?
With join() a thread can call another thread. Itself will be blocked until the other thread is terminated.
In what states is the thread alive?
RUNNABLE (Ready, Running)
BLOCKED, WAITING, TIMED_WAITING (“Suspended”)
What are the 6 different states of a thread?
NEW RUNNABLE BLOCKED TIMED_WAITING WAITING TERMINATED
What’s the advantage on implementing Runnable over extending the Thread class?
We can still extend a custom class (not only implement the Runnable). But when we extend the Thread class we can’t extend any further class because Java only supports single-inheritance.
How can you stop or terminate a thread?
- wait until run() ends
- we can also implement a flag variable marked as volatile to end the run loop
-> terminate() or stop() should not be used (deprecated), because we leave the thread in an inconsistent state
When is a thread alive?
From the moment when the thread has been started with start() the thread is alive. It stays alive as long as the run() method is still running.
What’s the purpose of an Executor?
To start a Runnable task with the method execute()
Example:
class ThreadPerTaskExecutor implements Executor{ public void execute(Runnable task) { new Thread(task).start(); } }
What can an ExecutorService do, that a simple Executor can’t do?
It can control and also stop task execution.
What happens when an ExecutorService calls shutdown()?
It stopps receiving tasks, waits until all accepted tasks have finished and then terminates the executor.
What’s the difference between shutdown() and shutdownNow()?
shutdown() waits until all tasks have finished running, shutdownNow() interrupts the running tasks.
Which class does ExecutorService extend?
Executors
e.g. ExecutorService executorService = Executors.newSingleThreadExecutor();
Which statements are true?
a) when a thread in a thread pool dies, a new thread pool is created
b) thread pools are created once
c) thread pools use a set of worker threads that can be reused
d) when a task is submitted the task always goes directly into the thread pool and waits until it can be executed
b) and c)
- > thread pools are created only once
- > the set of worker threads can be reused
(tasks don’t go directly into the pool, they first go into the blocking queue, which holds the task until a thread becomes available)
Name at least 3 different types of Thread Pools
- SingleThreadPool
- FixedThreadPool
- CachedThreadPool
- WorkStealingPool