Concurreny in Java:
StateLess:
Lazily Initialization / Loading??
Atomicity: ( thatagroupofstatementsappeartoexecuteasasingle,indivisible )State Consistency can be maintained by updating the relates state variables in an atomic operation.
RaceCondition: Lazy Initialization
java.util.concurrent.atomic package AtomicLong, threadSafe?? How Atommic Long works
Instrinsic Lock/Monitor Lock( act as Mutex ):(Reference to an Object serves as the lock) .Every java object can act as implicit Lock.Oreder for which Threads to acquire lock first Not Gauranteed by using intrinsic Lock,( as we use notify() Or notifyAll() ) hence Extrinsic Lock is to be used.
Intrinsic Locks are also ReEntrant: The Lock which is already held can be held again .
Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code blocks synchronized on the same monitor object
Example of ReEntrant Lock:
package text.reentrant;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReEntrantSample {
public static void main(String args[]) {
Sharedresource sharedresource = new Sharedresource();
Thread t1 = new Thread(sharedresource, "1");
Thread t2 = new Thread(sharedresource, "2");
t1.start();
t2.start();
t1.run();
t2.run();
}
}
class Sharedresource implements Runnable {
CommonResources cr = new CommonResources();
public void run() {
cr.anotherMethod();
}
}
class CommonResources {
private final Lock lock = new ReentrantLock();
public synchronized void getCount() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Thread--"
+ Thread.currentThread().getName() + " i is " + i);
}
} finally {
}
}
public synchronized void anotherMethod() {
System.out.println(" Inside another method ............. ");
getCount();
}
}
Extrinsic Lock: Lock lock = new ReEntrantLock(true) where true stands for fairness policy
and also deadlock situation can be avoided by using tryLock() of Lock class
Private Lock: Encapsulates the lock??? Advantages
Client Side Locking??????????
ReEntrant Lock Vs synchronized Difference:
1. fairness
2. tryLock()// using timeOut
3. determine the list of threads waiting.
EXAMPLE??
public class Widget {
public synchronized void doSomething() {
...
}
}
public class LoggingWidget extends Widget {
public synchronized void doSomething() {
System.out.println(toString() + ": calling doSomething");
super.doSomething();
}
}
Don't use lock to hold operations as I/O))???
Synchronization: Also determines NOT only mutual exclusion BUT also memory visibility(most updated value from shared memory) Hence reading/writing of threads to be on common Lock.
Volatile defines that the variable is shared among the Threads?? WHEN to USE???
Volatile gaurantees visibility but NOT atomicity
Avoid escapes: Don't use setters
class UnsafeStates {
private String[] states = new String[] {
"AK", "AL" ...
};
public String[] getStates() { return states; }
}
this reference escape during Construction????
Stack Confinemant: local variable are confined to stack
private to visibility is what final to immutuable
Volatile Refernce to Immutable Object Example???
final Objects are Immutable BUT final fields refering to Immutable Objects are NOT thread Safe
Objetcs defined using static initializer are threadSafe?????????How??
class CommonResources {
private final Lock lock = new ReentrantLock(true);
static int i;
static{
i = 0;
}
public void getCount() {
//synchronized(CommonResources.class){
lock.lock();
try {
for (; i < 2; i++) {
System.out.println("Thread--"
+ Thread.currentThread().getName() + " i is " + i);
}
} finally {
lock.unlock();
}
//}
}
}
Read Only objects are threadSafe
Java Monitor Pattern: each class has its own intrinsic lock
Vector and problem with Collections.synchronizedSet()????
Iterators are failfast as:
1. starvation
2. DeadLock
3.Scalability as lock being hold for long time and hence CPU usage is more
Solution: clone since it is thread confined.
Collections.synchonizedMap(provide exclusive access/Lock to entire HashMap) ConcurrentHashMap( weakly consistent though NOT fail fast)
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class ConcurrentHashMapSample {
public static void main(String args[]) {
ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<String, String>();
// Map<String,String> hashMap = new HashMap<String,String>();
// Collections.synchronizedMap(hashMap);
hashMap.put("core", "java");
hashMap.put("advanced", "J2ee");
for (Map.Entry<String, String> at : hashMap.entrySet()) {
hashMap.put(" newTopic ", "Sample");
System.out.println(" " + at.getKey() + " " + at.getValue());
}
}
}
Collections.synchronizedMap(hashMap) will lock the whole Map and other threads can't access at same time and also the map can't be modified while iteration is going on, though has advantage against ConcurrentHashMap in terms of Consistency, i.e. to keep the data updated for all threads.
Similarly,
Collections.synchonizedList === CopyOnWriteArrayList
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteSample {
public static void main(String args[]) {
CopyOnWriteArrayList<String> threadSafeList = new CopyOnWriteArrayList<String>();
//ArrayList<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("Java");
threadSafeList.add("J2EE");
threadSafeList.add("Collection");
//add, remove operator is not supported by CopyOnWriteArrayList iterator
Iterator<String> failSafeIterator = threadSafeList.iterator();
while(failSafeIterator.hasNext()){
//threadSafeList.add("Sample");
System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeIterator.next());
failSafeIterator.remove(); //not supported in CopyOnWriteArrayList in Java
}
}
}
BlockingQueue Vs Producer - Consumer pattern??
Synchronizers:
1. Latches
2. Future Tasks
3. Semaphores
4. Barriers
DisAdvantages of Unbounded ThreadCreation
ThreadPools: Types of ThreadPools: Cached, Single,FixedThreadPool
LifeCycle Methods of ExecutorService:
running, shutting down, and terminated.
Result Bearing Taks: Callable and FutureTasks
Real TIme Example???
Interupption policies and Cancellation via future
Newtaskfor????
ExecutorService: ShutDown options:
--- shutDown
---shutDownNow
PoisonPills:
https://dzone.com/articles/producers-and-consumers-part-3
ShutDown Hooks : To shutdown JVM
DeadLock in ThreadPool
Ahmdals Law??
StateLess:
Lazily Initialization / Loading??
Atomicity: ( thatagroupofstatementsappeartoexecuteasasingle,indivisible )State Consistency can be maintained by updating the relates state variables in an atomic operation.
RaceCondition: Lazy Initialization
java.util.concurrent.atomic package AtomicLong, threadSafe?? How Atommic Long works
Instrinsic Lock/Monitor Lock( act as Mutex ):(Reference to an Object serves as the lock) .Every java object can act as implicit Lock.Oreder for which Threads to acquire lock first Not Gauranteed by using intrinsic Lock,( as we use notify() Or notifyAll() ) hence Extrinsic Lock is to be used.
Intrinsic Locks are also ReEntrant: The Lock which is already held can be held again .
Synchronized blocks in Java are reentrant. This means, that if a Java thread enters a synchronized block of code, and thereby take the lock on the monitor object the block is synchronized on, the thread can enter other Java code blocks synchronized on the same monitor object
Example of ReEntrant Lock:
package text.reentrant;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReEntrantSample {
public static void main(String args[]) {
Sharedresource sharedresource = new Sharedresource();
Thread t1 = new Thread(sharedresource, "1");
Thread t2 = new Thread(sharedresource, "2");
t1.start();
t2.start();
t1.run();
t2.run();
}
}
class Sharedresource implements Runnable {
CommonResources cr = new CommonResources();
public void run() {
cr.anotherMethod();
}
}
class CommonResources {
private final Lock lock = new ReentrantLock();
public synchronized void getCount() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Thread--"
+ Thread.currentThread().getName() + " i is " + i);
}
} finally {
}
}
public synchronized void anotherMethod() {
System.out.println(" Inside another method ............. ");
getCount();
}
}
and also deadlock situation can be avoided by using tryLock() of Lock class
Private Lock: Encapsulates the lock??? Advantages
Client Side Locking??????????
ReEntrant Lock Vs synchronized Difference:
1. fairness
2. tryLock()// using timeOut
3. determine the list of threads waiting.
EXAMPLE??
public class Widget {
public synchronized void doSomething() {
...
}
}
public class LoggingWidget extends Widget {
public synchronized void doSomething() {
System.out.println(toString() + ": calling doSomething");
super.doSomething();
}
}
Don't use lock to hold operations as I/O))???
Synchronization: Also determines NOT only mutual exclusion BUT also memory visibility(most updated value from shared memory) Hence reading/writing of threads to be on common Lock.
Volatile defines that the variable is shared among the Threads?? WHEN to USE???
Volatile gaurantees visibility but NOT atomicity
Avoid escapes: Don't use setters
class UnsafeStates {
private String[] states = new String[] {
"AK", "AL" ...
};
public String[] getStates() { return states; }
}
this reference escape during Construction????
Stack Confinemant: local variable are confined to stack
private to visibility is what final to immutuable
Volatile Refernce to Immutable Object Example???
final Objects are Immutable BUT final fields refering to Immutable Objects are NOT thread Safe
Objetcs defined using static initializer are threadSafe?????????How??
class CommonResources {
private final Lock lock = new ReentrantLock(true);
static int i;
static{
i = 0;
}
public void getCount() {
//synchronized(CommonResources.class){
lock.lock();
try {
for (; i < 2; i++) {
System.out.println("Thread--"
+ Thread.currentThread().getName() + " i is " + i);
}
} finally {
lock.unlock();
}
//}
}
}
Read Only objects are threadSafe
Java Monitor Pattern: each class has its own intrinsic lock
Vector and problem with Collections.synchronizedSet()????
Iterators are failfast as:
1. starvation
2. DeadLock
3.Scalability as lock being hold for long time and hence CPU usage is more
Solution: clone since it is thread confined.
Collections.synchonizedMap(provide exclusive access/Lock to entire HashMap) ConcurrentHashMap( weakly consistent though NOT fail fast)
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class ConcurrentHashMapSample {
public static void main(String args[]) {
ConcurrentHashMap<String, String> hashMap = new ConcurrentHashMap<String, String>();
// Map<String,String> hashMap = new HashMap<String,String>();
// Collections.synchronizedMap(hashMap);
hashMap.put("core", "java");
hashMap.put("advanced", "J2ee");
for (Map.Entry<String, String> at : hashMap.entrySet()) {
hashMap.put(" newTopic ", "Sample");
System.out.println(" " + at.getKey() + " " + at.getValue());
}
}
}
Similarly,
Collections.synchonizedList === CopyOnWriteArrayList
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteSample {
public static void main(String args[]) {
CopyOnWriteArrayList<String> threadSafeList = new CopyOnWriteArrayList<String>();
//ArrayList<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("Java");
threadSafeList.add("J2EE");
threadSafeList.add("Collection");
//add, remove operator is not supported by CopyOnWriteArrayList iterator
Iterator<String> failSafeIterator = threadSafeList.iterator();
while(failSafeIterator.hasNext()){
//threadSafeList.add("Sample");
System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeIterator.next());
failSafeIterator.remove(); //not supported in CopyOnWriteArrayList in Java
}
}
}
BlockingQueue Vs Producer - Consumer pattern??
Synchronizers:
1. Latches
2. Future Tasks
3. Semaphores
4. Barriers
DisAdvantages of Unbounded ThreadCreation
ThreadPools: Types of ThreadPools: Cached, Single,FixedThreadPool
LifeCycle Methods of ExecutorService:
running, shutting down, and terminated.
Result Bearing Taks: Callable and FutureTasks
Real TIme Example???
Interupption policies and Cancellation via future
Newtaskfor????
ExecutorService: ShutDown options:
--- shutDown
---shutDownNow
PoisonPills:
https://dzone.com/articles/producers-and-consumers-part-3
ShutDown Hooks : To shutdown JVM
DeadLock in ThreadPool
Ahmdals Law??
No comments:
Post a Comment