Threads Flashcards
What is concurrency?
Execution of multiple threads or processes in same time
What is context switching?
Process of returning to threads running state after its state change state at some point in time
Can threads have priorities?
They can be prioritized over other threads
How can we create new threads?
new Thread(Callable).start()
run() method doesn’t start a thread.
or
A class can implement Callable or Runnable interfaces, and then start() method can be executed.
What is lifecycle of a thread?
- NEW -> start()
- RUNNABLE
2a. BLOCKED - if resource is blocked. shared resource is lock.
2b. WAITING - thread is waiting for other thread to wake it or complete - notify(), notifyAll()
2c. TIMED_WAITING - same as WAITING, but it contains time limit - -> run() -> TERMINATED
What is liveliness?
Applications responsivity.
Usually it is hurt when some thread or threads are constantly in WAIT or BLOCKED.
What is deadlock?
It is a case when two or more threads are holding a shared resource which they all need.
What is starvation?
Occurrence when some threads cannot get ahold of resources they need because other threads are constantly locking them away. Happens for eg. when prioritised threads always get resources before lower prioritised threads.
What is livelock?
Situation where threads lock each other, but instead of going into WAITING or BLOCKED state, they keep on trying to get ahold of a locked resource.
What collections are used in concurrency?
ConcurrentHashMap
ConcurrentLinkedQueue
ConcurrentSkipListMap
ConcurrentSkipListSet
CopyOnWriteArrayList
CopyOnWriteArraySet
LinkedBlockingQueue
All can be instantiated by Collections.
ConcurrentHashMap
Thread-safe version of HashMap. Allows concurrent reads and a configurable number of concurrent writes.
Use cases: High-concurrency scenarios requiring frequent reads and occasional writes. Good for caching and shared mappings in multi-threaded applications.
ConcurrentLinkedQueue
Characteristics: Non-blocking, thread-safe queue implementation based on linked nodes.
Use cases: When you need a high-performance, scalable queue for multiple producers and consumers.
ConcurrentSkipListMap
Characteristics: Sorted, thread-safe map based on a skip list data structure. Provides expected O(log n) time for most operations.
Use cases: When you need a sorted, concurrent map with good performance for simultaneous reads and writes.
ConcurrentSkipListSet
Characteristics: Sorted, thread-safe set based on ConcurrentSkipListMap.
Use cases: When you need a sorted, concurrent set with good performance for simultaneous reads and writes.
CopyOnWriteArrayList
Characteristics: Thread-safe variant of ArrayList where all mutative operations create a fresh copy of the underlying array.
Use cases: When reads greatly outnumber writes, and iteration is very common. Often used for listener lists in event-driven programming.