Concurrency in Java

  • Process: A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process are allocated to it via the operating system, e.g. memory and CPU time.
  • Threads: threads are so called lightweight processes which have their own call stack but an access shared data. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache. Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files


The Executor and Executor Services are defined in java concurrency package(java.util.concurrent package).

2. A very good example of Multi Threading is Garbage Collection in java.The Garbage Collector Thread works Independently.

3. For using Synchronization there are 2 approaches
  •     To use the java apis and use synchronized elements like hashtable
  • more advanced option use threads and related functionalities.
4. At any point in time the thread will be in the following states

                                    Terminated
                                            |
                                            |
                        new --- > runnable ---> Waiting
                                            |
                                            | 
                                       Timed Waiting    

5.A new thread begins its life in New State until the run method is invoked on it.

6.A waiting thread can only be bought back to runnable state by another thread.

An InterruptedException is thrown when a sleeping thread is interrupted.

whenever an interrupt is called on a thread an interrupt flag is set and this can be queried using Thread.Interrupted();The interrupt flag wont be cleared until the thread exits calling interuptedException.

When a join is called on a new thread object in current thread, the current thread goes into wait mode until the thread on which join is called is executed or until an interrupt is raised on current thread. 

Eg: public void run() {
        int i=0;
        Thread t1=new Thread(secThread);
        t1.start();
        System.out.println("Second thread spawned");
        try {
            t1.join();
        } 

}

Here the main thread with run method waits until the t1 is done or until an interrupt is raised on main thread.

An interrupt need not require a sleep or join.Any moment an interrupt is called the status flag is set and using that flag check as interrupted() we can stop the tread execution.

7.A timed waiting thread can be brought back to runnable state if another thread signals it or when the time period is over.

8.The Thread in the runnable state encompasses 2 other states.These states are hidden from the JVM and is completely handled by the operating system.The thread in a runnable state in the beginning is in Ready state and the operating system allocates some processor time called Time slice or Quantum for the thread. The allocating processor time is called dispatching of the thread and this is done by the operating system scheduler,Scheduling is based on thread priority.

9.Normally there are three main priorities for a thread Min_Priority(1) , Normal_Priority and Max_Priority. The threads which are having highest priority are having more precedence than the Normal one. however priority cannot guarantee the order and by default every thread has normal priority and new thread has priority of the created thread.

10. The priorities are defined in Thread class and it is better not to use thread class and use runnable.

Difference wait and sleep
--------------------------------- 
  • The main difference between wait and sleep  is when waiting the thread will release the acquired intrinsic lock and while sleeping it will hold on to the acquired lock. 
  • wait can only be called from a synchronized method or block were as sleep has no such requirement.
  • Sleep is a static method that is called on the thread were as wait is called on an object.
  • Sleeping thread directly becomes runnable were as waiting thread first wait to acquire lock.
11. The yield method will pause the current thread until all other threads with same priority or more are executed.

Memory Consistency error happens when different threads have different views of same data.

Memory Consistency error can be avoided by ensuring happens-before relationship. This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement. 

Synchronized Methods
-------------------------

1. The Method when synchrozied only one thread can access the method at a time so that the happens-before relatioship is always ensured.
2. The synchrozed method ensures that happens- before agrrement is fulfilled for further invocations of functions.

The final variable can be used in synchronized methods as there values cannot be modified.

Synchronization is built around an entity called Intrinsic Lock or Monitor Lock. Every thread tries to acquire an Intrinsic or monitor lock on an object then it gets exclusive access to the objects state and also it ensures that the happens-before realtion is maintained.

When a thread access the synchronized method then automatically it attains the intrinsic lock on that object.and if the method is static then the lock is obtained on the class object of the class.

When to Lock
--------------

  •  Always lock during updates to object fields.
  •  Always lock during access of possibly updated object fields.
  •  Never lock when invoking methods on other objects.

This gives basic guidelines but sure has exceptions and refinements.

Another way to acheive synchronization is through synchronized statements.The synchronized statements helps to acheive a fine grained synchronization.

While using wait we should always use it along with guardian block in a loop.this is because the thread need not be invoked by the right thread but can also get invoked because of no notification,interrupt or timing out so called spurious wake up and this can cause unexpected result in production.


The main difference between Cuncurrent hashMap and Hashtable is that if the hashtable size increases then there is a huge perfomance degrade during iterations and all as the entire collection is locked. however concurrent hashmap is more advanced and has segementation were only small part is locked at a time.same is applicable for the Collections.synchroziedMap() method.

Comments

Popular posts from this blog

'jasypt.encryptor.password' or one of ['jasypt.encryptor.privateKeyString', 'jasypt.encryptor.privateKeyLocation'] must be provided for Password-based or Asymmetric encryption

Field or property 'jobParameters' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - Spring Batch

Couldn't store job: Unable to serialize JobDataMap for insertion into database because the value of property 'jobLauncher' is not serializable