Showing posts with label Multi Threading. Show all posts
Showing posts with label Multi Threading. Show all posts

Sunday, 6 November 2016

Java Source World: Synchronization in Java

Synchronization in Java | Java Source World

                                                                                   Java Source World                   A Java quick reference blog



Synchronization in Java



Mechanism to control the access of shared resource by multiple threads.
When multiple thread access any shared resource simultaneously , it may result in data in consistency. Hence we can use synchronization concept to ensure the data consistency.
Synchronization can be achieved by using a modifier called 'synchronized'. 
It can be implemented in 2 ways

  • Synchronized Method
  • Synchronized Block/statement. 

Synchronized Method:



When we need to synchronize a method , we can do it by adding modifier "synchronized" to method header.
We can define synchronize methods when we have access to source code.

A java class can have multiple synchronized methods. But only one synchronized method can execute at any point of time.Hence the shared resource of that Class/Object can be assured through that method. This guarantees that no 2 threads can access shared resource simultaneously.

When a thread is executing a synchronized method it will not release the CPU unless it finishes the execution completely.Even if the thread goes to Block/Wait/sleep state.


Example: Synchronizing a method

       synchronized public void withdraw(double amount){
                  //do something
            }



Synchronized Block/statement:


When we do not have access to source code we cannot synchronize methods in that class.This kind of situation will arise when we third party libraries purchased from some vendor.It ensure data consistency.

Example: Synchronizing a block or statement.

         synchronized(obj){
                  obj.run();
            }

In the above code, obj is the reference of the object.



There is no guarantee that thread priority works always. If JVM doesn't honor the specified priority then priority doesn't work.



Other posts you may like to read:



                                                                      Java Source World              A Java quick reference blog



Read More »

Wednesday, 26 October 2016

Java Source World: Multithreading - Joining threads | Join() method | how Join() method works


How Join() method works in Multithreaded environment:


Multithreading - Joining threads | Join() method | how Join() method works | Java Source World
Sometimes one thread needs to know when another thread is ending. In java, isAlive() and join() are two different methods to check whether a thread has finished its execution.


The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false.

Syntax:  final boolean isAlive()


But, join() method is used more commonly than isAlive(). This method waits until the thread on which it is called terminates.

Syntax:  final void join() throws InterruptedException


Using join() method, we tell our thread to wait until the specified thread completes its execution. There are overloaded versions of join() method, which allows us to specify time for which you want to wait for the specified thread to terminate.     

Syntax:  final void join(long milliseconds) throws InterruptedException

Example:

package com.core.alljavaconcepts.multithreading;

public class JoinExample {//Main class
      public static void main(String[] args) {
            Thread th1 = new Thread(new MyClass(), "Thread1");
            Thread th2 = new Thread(new MyClass(), "Thread2");
            //start first thread
            th1.start();
            //Start second thread once th1 is dead
            try {
                  th1.join();
            } catch (InterruptedException e) {
                  e.printStackTrace();
            }
            //start second thread
           
            //Display below message once the th2 is dead
            try {
                  th2.join();
            } catch (InterruptedException e) {
                  e.printStackTrace();
            }
            System.out.println("Threads completed");
      }  
}
class MyClass implements Runnable{
      @Override
      public void run() {
            Thread t = Thread.currentThread();
            System.out.println(t.getName()+" Strated ");
           
            try {
                  t.sleep(4000);
            } catch (InterruptedException e) {
                  e.printStackTrace();
            }
            System.out.println(t.getName()+" Ended ");
            System.out.println("------------------------");
      }
     
}
As per above example, first the thread one th1 starts its execution, and once after it completes its execution only the second thread th2 will start exeuting and completes the execution and displayes the last statement.

Lets see the out put of the above example code: 
That is as fallows:

Console out put:

Thread1 Strated 
Thread1 Ended 
------------------------
Thread2 Strated 
Thread2 Ended 
------------------------
Threads completed






You may also like the fallowing posts:




Read More »