How to create a thread?
Different types of ExecutorService
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?
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();
Lock Vs synchronzed
1. Lock have more unblocking features: tryLock() tryLock(time) lockInterruptly() newCondition(); - await/signal/signalAll
Lock Vs synchronzed
How AtomicXX implemented?
CAS - compare and set operation:
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 ?
What is Java memory model?
A set of rule that JVM follow on memory operation/information sharing:
What is FutureTask<> ?
2. can be submitted to executor to execute
What happens when submit to a executor when it is already full?
TO_DO
Best practice for multi-thread?
What is fork/join pool in Java?
How to implement?
Definition
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.
https: //www.pluralsight.com/guides/introduction-to-the-fork-join-framework
https: //www.baeldung.com/java-fork-join
Synchronized keyword Vs Lock
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.
Why Synchronized is expensive comparing with normal method?