Concurrency Flashcards
How to create a thread?
- 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: - less cost than create/destroy thread for each task, have ready to use thread, also keep them live
- Have total thread number control
Different types of ExecutorService
- newCachedThreadPool()
2.newFixedThreadPool()
newly added task will be added to a queue when there is no avaliable thread
3.newScheduledThreadPool()
4.newSingleThreadExecutor()
Different Status of a Thread
NEW RUNNABLE RUNNING BLOCKED WAITING TIMED_WAITING
Thread join(), yield(), isInterrupted()
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();
}
Different Status of a Thread
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
What is Java demon thread?
- Threads that not prevent JVM exit, mainly to provide foundational service for user thread.
- GC thread.
- setDaemon(true)
synchronised keyword on object method/static method
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
Lock Vs synchronzed
1. Lock have more unblocking features: tryLock() tryLock(time) lockInterruptly() newCondition();
- but can forget to unlock, so always put in finally block
Lock Vs synchronzed
1. Lock have more unblocking features: tryLock() tryLock(time) lockInterruptly() newCondition(); - await/signal/signalAll
- but can forget to unlock, so always put in finally block
Lock Vs synchronzed
- Lock have more unblocking features:
tryLock()
tryLock(time)
lockInterruptly()
newCondition(); - await/signal/signalAll
read/write lock more efficient. - but can forget to unlock, so always put in finally block
How AtomicXX implemented?
CAS - compare and set operation:
- There is a M
- 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
Concurrent Collections
ConcurrentHashMap
CopyOnWriteArrayList
Other questions
How to stop executor service?
how executor service works internally?
Java memory model/happen before replation shop
What is ThreadLocal ?
- A class wrapper to wrap create expensive objects
- Provide per thread per copy.
- Compare with local variable, reduce the no. of objs created also have thread safety without synchronisation/immutability
What is Java memory model?
A set of rule that JVM follow on memory operation/information sharing:
- Volitine variable rule - every write happens before subsquent read.
- Monitor lock rule - every unlock happens before lock on that monitor lock