Threads Flashcards

1
Q

What is concurrency?

A

Execution of multiple threads or processes in same time

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

What is context switching?

A

Process of returning to threads running state after its state change state at some point in time

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

Can threads have priorities?

A

They can be prioritized over other threads

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

How can we create new threads?

A

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.

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

What is lifecycle of a thread?

A
  1. NEW -> start()
  2. 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
  3. -> run() -> TERMINATED
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is liveliness?

A

Applications responsivity.
Usually it is hurt when some thread or threads are constantly in WAIT or BLOCKED.

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

What is deadlock?

A

It is a case when two or more threads are holding a shared resource which they all need.

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

What is starvation?

A

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.

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

What is livelock?

A

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.

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

What collections are used in concurrency?

A

ConcurrentHashMap
ConcurrentLinkedQueue
ConcurrentSkipListMap
ConcurrentSkipListSet
CopyOnWriteArrayList
CopyOnWriteArraySet
LinkedBlockingQueue

All can be instantiated by Collections.

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

ConcurrentHashMap

A

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.

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

ConcurrentLinkedQueue

A

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.

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

ConcurrentSkipListMap

A

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.

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

ConcurrentSkipListSet

A

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.

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

CopyOnWriteArrayList

A

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.

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

CopyOnWriteArraySet

A

Characteristics: Set implementation backed by CopyOnWriteArrayList.
Use cases: Similar to CopyOnWriteArrayList, but when you need set semantics (no duplicates).

17
Q

LinkedBlockingQueue

A

Characteristics: Optionally bounded blocking queue based on linked nodes.
Use cases: Producer-consumer scenarios, especially when you need to block producers when the queue is full or consumers when it’s empty.

18
Q

What is pooling in concurrency?

A

Checking of some data in some interval - is thread finished?

19
Q

What is race condition?

A

Situation where two or more processes or threads access shared data or resources simultaneously, and the final outcome depends on the timing or order of their execution. Eg. two users with same name are created at the same time.

20
Q

Decomposition using streams?

A

stream.parallel() or parallelStream()

21
Q

Reduction using streams?

A

reduce(identity, accumulator, combiner)
collect(supplier -> new collection, accumulator, combiner)

22
Q

Runnable?

A

Type of thread interface that implements start of a new thread, but it always returns null.

service.submit(() -> …) get()

23
Q

Callable?

A

Type of thread interface that implements start of a new thread, but it returns defined type by generic.

Future<T> result = service.submit(() ->... get()</T>

24
Q

What methods do Executors services have?

A

execute() - doesn’t return anything
submit() - returns Future
invokeAll() - executes all provided threads
invokeAny() - executes random provided thread

25
Q

What methods does Future have?

A

get() - waits for thread to complete and then return the result
get(timeout) - same as get(), but has timeout
isDone()
isCancelled()
cancel()

26
Q

What service is used to run single thread?

A

Executors.newSingleThreadExecutor()

27
Q

What is lifecycle of thread executor?

A

ACTIVE state - accepts new tasks and executes tasks
SHUTTING DOWN state - after shutdown() is ran, accepting new tasks is disabled, but execution of running tasks is happening
SHUTDOWN state - after isShutdown() is confirmed, no new tasks and task execution is allowed. State can be confirmed by isTerminated() or isShutdown()

28
Q

How can we run scheduled threads?

A

Using Executors.newSingleThreadScheduledExecutor()

29
Q

What methods does scheduled thread executor have?

A

schedule(Callable)
schedule(Runnable)
scheduledAtFixedRate - executes tasks without regarding previous tasks
sheduleWithFixedDelay - executes tasks when previous tasks complete

30
Q

What tools do we use to ensure thread safety?

A

synchronized keyword
Atomic classes
volatile keyword
Reetainent locks
Cyclic barriers

31
Q

synchronized keyword

A

Using monitors, or locks to ensure mutual exclusion (only one thread does its work).
Monitor or lock can be any object.
When thread comes to shared monitor, it locks sync. block to other threads. Any other thread that comes to that lock is blocked. When locking thread finishes, it releases the lock.

They can be used on code blocks or methods.

32
Q

What are downsides of “synchronized”?

A

Performance overhead
Risk of deadlock because it can easily lead to bad ordering of locking and unlocking

33
Q

Atomic classes?

A

Used to share value between threads. Threads wait until atomic operation is completed. They are consistent, but order of execution is not known.

34
Q

What are common atomic classes?

A

AtomicInteger
AtomicBoolean
AtomicLong

35
Q

What are common atomic classes methods?

A

get
set
getAndSet
incrementAndGet
getAndIncrement
decrementAndGet
getAndDecrement

36
Q

volatile keyword

A

Used on instance and static variables.
Cannot use compound actions on them (i++).
It ensures that only one thread is reading and writing to it.
Not thread safe because it doesn’t solve race conditions.
Data may not be consistent.

37
Q

RetainentLock

A

Lock lock = new RetainentLock()
try {
lock.lock()
// protected code
}

You can optionally add “finally” and put lock.unlock() in. There must be exact number of unlocks as the number of locks.

RetainentLock(true) can be set for “fairness”, which thread requests lock first will be using lock first. It should be used only if necessary, because it is not performant.

38
Q

What are common RetainentLock methods?

A

lock
unlock
tryLock -> locks and returns boolean
tryLock(TimeUnit) -> locks or waits specified time to get the key

39
Q

CyclicBarrier

A

Can be used to control parts of code by blocking threads from advancing before all threads get to specific part of code.

var c = new CyclicBarrier(4)

or

var c = new CyclicBarrier(4, Runnable). Runnable is optional and is run when barrier is hit.

try {
// …
c.await();
// …
} catch (BrokenBarrierException e) {
// …
}