Concurrency Flashcards

1
Q

How to create a thread?

A
  1. Extends the Thread class, override run(). call start()
    2.Implement the Runnable interface, new Thread(new MyRunnable()).start();
    3.ExecutorService pool = Executors.
    newFixedThreadPool(n)
    used when have long running tasks
    newCachedThreadPool()
    used when have big amounts of short tasks
    adv:
  2. less cost than create/destroy thread for each task, have ready to use thread, also keep them live
  3. Have total thread number control
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Different types of ExecutorService

A
  1. newCachedThreadPool()
    2.newFixedThreadPool()
    newly added task will be added to a queue when there is no avaliable thread
    3.newScheduledThreadPool()
    4.newSingleThreadExecutor()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Different Status of a Thread

A
NEW
RUNNABLE
RUNNING
BLOCKED
WAITING
TIMED_WAITING
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Thread join(), yield(), isInterrupted()

A

t2.join() - When we invoke the join() method on a thread, the calling thread goes into a waiting state. It remains in a waiting state until the referenced thread terminates.

If the referenced thread was already terminated or hasn’t been started, the call to join() method returns immediately.
“Happens-before”: This means that when a thread t1 calls t2.join(), then all changes done by t2 are visible in t1 on return

yield() - no release lock
Thread. sleep() will cause currently executing thread to stop execution and relinquish the CPU to allow Thread scheduler ot allocate CPU to another thread or same thread depends upon Thread scheduler. Thread. yield() also used to relinquish CPU but behavior of sleep() is more determined than yield across platform.

t2.isInterrupted() - check if the flag is true
t2.interrupt() - interrupt t2
Thread.interruped() - check if current thread is interrupted, and clear the status(set to false)

CATCH(InterruptedException){
Thread.currentThread().interrupt();
}

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

Different Status of a Thread

A
NEW - thread just created
RUNNABLE - cpu allocate stack, PC registers
RUNNING - start execution
BLOCKED - 
waiting for I/O to complete, 
waiting for a  monitor lock

WAITING - waiting indefinitly for another thread to perform an action and give a signal
Object.wait with no timeout
Thread.join with no timeout

TIMED_WAITING
Thread.sleep
Object.wait with no timeout
Thread.join with no timeout

TERMINATED

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

What is Java demon thread?

A
  1. Threads that not prevent JVM exit, mainly to provide foundational service for user thread.
  2. GC thread.
  3. setDaemon(true)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

synchronised keyword on object method/static method

A

object method - lock on the object access

static method - synchronised on all the thread calling the method, as static are stored in medaspace that is shared

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

Lock Vs synchronzed

A
1. Lock have more unblocking features:
tryLock()
tryLock(time)
lockInterruptly()
newCondition();
  1. but can forget to unlock, so always put in finally block
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Lock Vs synchronzed

A
1. Lock have more unblocking features:
tryLock()
tryLock(time)
lockInterruptly()
newCondition();  - await/signal/signalAll
  1. but can forget to unlock, so always put in finally block
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Lock Vs synchronzed

A
  1. Lock have more unblocking features:
    tryLock()
    tryLock(time)
    lockInterruptly()
    newCondition(); - await/signal/signalAll
    read/write lock more efficient.
  2. but can forget to unlock, so always put in finally block
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How AtomicXX implemented?

A

CAS - compare and set operation:

  1. There is a M
  2. Set M to B only when M ‘s current value is A

Why it is better than lock?
Avoid thread suspend/resume, when casing is failed, just moving to next steps.

Java Atomic variables? - only used when concurrency is  not very high, thread keep retry to add the counter
AtomicInteger
AtomicLong
AtominBoolean
AtomicReference
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Concurrent Collections

A

ConcurrentHashMap

CopyOnWriteArrayList

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

Other questions

A

How to stop executor service?
how executor service works internally?
Java memory model/happen before replation shop

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

What is ThreadLocal ?

A
  1. A class wrapper to wrap create expensive objects
  2. Provide per thread per copy.
  3. Compare with local variable, reduce the no. of objs created also have thread safety without synchronisation/immutability
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is Java memory model?

A

A set of rule that JVM follow on memory operation/information sharing:

  1. Volitine variable rule - every write happens before subsquent read.
  2. Monitor lock rule - every unlock happens before lock on that monitor lock
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is FutureTask<> ?

A
  1. Wrapper of a runnable

2. can be submitted to executor to execute

17
Q

What happens when submit to a executor when it is already full?

A

TO_DO

18
Q

Best practice for multi-thread?

A
  1. Using thread factory to give each thread a name
  2. prefer concurrent collection over synchronised collection
  3. minimize synchronzed block
19
Q

What is fork/join pool in Java?

How to implement?

A

Definition

  1. a implementation of executor service
  2. Mainly used for tasks can be break into smaller tasks recursively, to maximum usage of the CPU processing powers

How to implement
1. ForkJoinTask
ForkJoinTask fork() - Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool() if not inForkJoinPool().

 V join()
Returns the result of the computation when it is done. This method differs from get() in that abnormal completion results in RuntimeException or Error, not ExecutionException, and that interrupts of the calling thread do not cause the method to abruptly return by throwing InterruptedException.
Collection invokeAll(Collection tasks)
Forks all tasks in the specified collection, returning when isDone holds for each task or an (unchecked) exception is encountered, in which case the exception is rethrown.
Need to call join() on each to fetch result

int result = forkJoinPool.invoke(customRecursiveTask); performing this task, awaits its completion if necessary, and returns its result, or throws an (unchecked) RuntimeException or Error if the underlying computation did so.

  1. extends RecursiveAction(runnable, no return value)/RecursiveTask(callable return a V ){override compute(){ invokeAll(new task1, new task2)}}

https: //www.pluralsight.com/guides/introduction-to-the-fork-join-framework
https: //www.baeldung.com/java-fork-join

20
Q

Synchronized keyword Vs Lock

A

https://stackoverflow.com/questions/36371149/reentrantlock-vs-synchronized-on-cpu-level
1. If you’re simply locking an object, I’d prefer to use synchronized
in general consider that synchronized is just an easy-to-use and concise approach of locking.

2.Some time ago ReentrantLock was way faster under certain conditions (high contention for example), but now Java uses different optimizations techniques (like lock coarsening and adaptive locking) to make performance differences in many typical scenarios barely visible to the programmer.

  1. Lock provides
  2. lock polling, timed lock waits, and interruptible lock waits.
  3. Read write lock to improve performance
  4. more complex code structures than Synchronized

Why Synchronized is expensive comparing with normal method?

  1. read everything from main memory
  2. do the job
  3. flush the cache to memory
  4. prevents compiler as well as cpu reordering of instructions