SlideShare une entreprise Scribd logo
1  sur  21
Concept of Synchronization




                             1
Objectives

On completion of this period, you would be
able to learn

•   Synchronization
•   Monitors
•   Unsynchronized Example
•   Locking Object
•   Synchronized Examples



                                             2
Recap

In this previous class, you have learnt
• Concept of thread priority
• Relevant methods and constants
• Relevant programs




                                          3
Synchronization

• We learnt in operating systems the concept of
  critical section
  • Two or more processes shares a resource like
    variables, files etc
  • They need to be synchronized, so that, the state
    of the shared resource is consistent
  • The same concept can be applied to the treads as
    well




                                                       4
Synchronization
                                    Contd . . .

• What is synchronization?

  • Concurrently running threads may require outside
    resources (shared resources) or methods
  • Need to communicate with other concurrently running
    threads to know their status and activities
  • Example: Producer-Consumer problem




                                                          5
Monitor

• An object which is used as a mutually
  exclusive lock
• Only one thread can acquire a monitor at a
  time
• All other threads attempting to enter the
  monitor will be suspended
• Every java object has its own implicit monitor
• Such     monitors    can     be    used     for
  synchronization


                                                    6
Unsynchronized Example

class TwoStrings {
     static void print(String str1, String
   str2) {
     System.out.print(str1);
     try {
        Thread.sleep(500);
      } catch (InterruptedException ie) {
     }
     System.out.println(str2);
   }
 }

                                             7
Unsynchronized Example                     Contd . . .
class PrintStringsThread implements Runnable {
  Thread thread;
                                          A Thread implementation
  String str1, str2;                      class
PrintStringsThread(String str1, String str2) {
    this.str1 = str1;
    this.str2 = str2;
    thread = new Thread(this);
    thread.start();
  }
  public void run() {
    TwoStrings.print(str1, str2);        Shared Resource

  }
}
                                                                      8
Unsynchronized Example
                                                 Contd . . .

class TestThread {
   public static void main(String args[]) {
     new PrintStringsThread("Hello ", "there.");
     new PrintStringsThread("How are ", "you?");
     new PrintStringsThread("Thank you ", "very much!");
   }
                            Output
 }

                               Expected output is
                               Hello there
                               How are you?
                               Thank you very much!
                                                               9
Locking of an object

• Assures that only one thread gets to access a
  particular method
• Java allows you to lock objects with the use of
  monitors
  • All Java objects have their own implicit monitor
  • Object enters the implicit monitor when the object's
    ‘synchronized’ method is invoked
  • Once an object is in the monitor, the monitor makes
    sure that no other thread accesses the same object



                                                           10
Locking of an object
                                          Contd . . .
• Monitor is implemented in Java through
  ‘synchronized’ keyword
• The ‘synchronized’ keyword can be used in two
  ways:
  1. Prefixed to the header of the method definition
  2. Can synchronize the object of which the method is a
    member of
     • synchronized (<object>) {
       //statements to be synchronized
     }


                                                           11
First Approach : synchronized
                                      Use of synchronized keyword
class TwoStrings {
   synchronized static void
   print(String str1, String str2) {
     System.out.print(str1);
     try {
       Thread.sleep(500);
      }catch(InterruptedException ie) {
     }
     System.out.println(str2);
   }
 }
                                                                    12
Contd . . .
          First Approach : synchronized
class PrintStringsThread
       implements Runnable {
  Thread thread;
  String str1, str2;

PrintStringsThread(String str1,String str2) {
    this.str1 = str1;
    this.str2 = str2;
    thread = new Thread(this);
    thread.start();
  }
  public void run() {
    TwoStrings.print(str1, str2);
  }
}       Shared Resource
                                                        13
Contd . . .
          First Approach : synchronized

class TestThread {
   public static void main(String args[]) {
     new PrintStringsThread("Hello ", "there.");
     new PrintStringsThread("How are ", "you?");
     new PrintStringsThread("Thank you ", "very much!");
   }
                            Output
 }



                                  Got the output as
                                  expected
                                                                    14
Second Approach : synchronized
class TwoStrings {
   static void print(String str1, String str2) {
     System.out.print(str1);
     try {
       Thread.sleep(500);
     }catch(InterruptedException ie){ }
     System.out.println(str2);
   }
 }
class PrintStringsThread implements Runnable {
   Thread thread;
   String str1, str2;
   TwoStrings ts;
                                                   15
Second Approach : synchronized                        Contd . . .


PrintStringsThread(String str1, String str2, TwoStrings ts)
 {
     this.str1 = str1;
     this.str2 = str2;
     this.ts = ts;
     thread = new Thread(this);
     thread.start();
}
                                  Use of synchronized statement
public void run() {
    synchronized (ts) {
       ts.print(str1, str2);
    }
  }
}


                                                                          16
Contd . . .
     Second Approach : synchronized

class TestThread {
   public static void main(String args[]) {
     new PrintStringsThread("Hello ", "there.");
     new PrintStringsThread("How are ", "you?");
     new PrintStringsThread("Thank you ", "very much!");
   }
 }
                          Output




                                   Got the output as
                                   expected
                                                                     17
Summary

• In this class we have discussed
  •   Problem of synchronization
  •   Monitors and locking objects
  •   Two approaches of using synchronized keyword
  •   Relevant example programs


• In the next lesson we look at Inter-Thread
  Communication



                                                     18
Quiz

1. Which concept is used by Java in inter-thread-
   synchronization

  A.   Process
  B.   Monitor
  C.   Multitasking
  D.   None




                                                    19
Quiz Contd..
2. Which keyword is used for synchronization in
  Java ?

  A.   synchronize
  B.   synchronised
  C.   synchronized
  D.   synchronizing




                                                  20
Frequently Asked Questions

1.   Explain the concept of synchronization
2.   What is monitor?
3.   How monitor is implemented in Java?
4.   What are the different ways of using
     ‘synchronized’ keyword ?




                                              21

Contenu connexe

Tendances (20)

Wrapper class
Wrapper classWrapper class
Wrapper class
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java threads
Java threadsJava threads
Java threads
 
Files in java
Files in javaFiles in java
Files in java
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiers
 
JDBC
JDBCJDBC
JDBC
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in java
 
Applets
AppletsApplets
Applets
 
Java rmi
Java rmiJava rmi
Java rmi
 
Overview of UML Diagrams
Overview of UML DiagramsOverview of UML Diagrams
Overview of UML Diagrams
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
 
java Features
java Featuresjava Features
java Features
 
Object oriented testing
Object oriented testingObject oriented testing
Object oriented testing
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 

En vedette

2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc driversmyrajendra
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1myrajendra
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 

En vedette (8)

4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Data type
Data typeData type
Data type
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
Fundamentals
FundamentalsFundamentals
Fundamentals
 

Similaire à Synchronization.37

Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
ThreadProperties
ThreadPropertiesThreadProperties
ThreadPropertiesmyrajendra
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
Java class 6
Java class 6Java class 6
Java class 6Edureka!
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptxcreativegamerz00
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 

Similaire à Synchronization.37 (20)

22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
ThreadProperties
ThreadPropertiesThreadProperties
ThreadProperties
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Java class 6
Java class 6Java class 6
Java class 6
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java String
Java String Java String
Java String
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
04 threads
04 threads04 threads
04 threads
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Java
Java Java
Java
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 

Plus de myrajendra

Plus de myrajendra (20)

Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 
Properties
PropertiesProperties
Properties
 
Java.sql package
Java.sql packageJava.sql package
Java.sql package
 
Interface callable statement
Interface callable statementInterface callable statement
Interface callable statement
 
Interface result set
Interface result setInterface result set
Interface result set
 
Interface database metadata
Interface database metadataInterface database metadata
Interface database metadata
 
Interface connection
Interface connectionInterface connection
Interface connection
 
Indexing
IndexingIndexing
Indexing
 

Synchronization.37

  • 2. Objectives On completion of this period, you would be able to learn • Synchronization • Monitors • Unsynchronized Example • Locking Object • Synchronized Examples 2
  • 3. Recap In this previous class, you have learnt • Concept of thread priority • Relevant methods and constants • Relevant programs 3
  • 4. Synchronization • We learnt in operating systems the concept of critical section • Two or more processes shares a resource like variables, files etc • They need to be synchronized, so that, the state of the shared resource is consistent • The same concept can be applied to the treads as well 4
  • 5. Synchronization Contd . . . • What is synchronization? • Concurrently running threads may require outside resources (shared resources) or methods • Need to communicate with other concurrently running threads to know their status and activities • Example: Producer-Consumer problem 5
  • 6. Monitor • An object which is used as a mutually exclusive lock • Only one thread can acquire a monitor at a time • All other threads attempting to enter the monitor will be suspended • Every java object has its own implicit monitor • Such monitors can be used for synchronization 6
  • 7. Unsynchronized Example class TwoStrings { static void print(String str1, String str2) { System.out.print(str1); try { Thread.sleep(500); } catch (InterruptedException ie) { } System.out.println(str2); } } 7
  • 8. Unsynchronized Example Contd . . . class PrintStringsThread implements Runnable { Thread thread; A Thread implementation String str1, str2; class PrintStringsThread(String str1, String str2) { this.str1 = str1; this.str2 = str2; thread = new Thread(this); thread.start(); } public void run() { TwoStrings.print(str1, str2); Shared Resource } } 8
  • 9. Unsynchronized Example Contd . . . class TestThread { public static void main(String args[]) { new PrintStringsThread("Hello ", "there."); new PrintStringsThread("How are ", "you?"); new PrintStringsThread("Thank you ", "very much!"); } Output } Expected output is Hello there How are you? Thank you very much! 9
  • 10. Locking of an object • Assures that only one thread gets to access a particular method • Java allows you to lock objects with the use of monitors • All Java objects have their own implicit monitor • Object enters the implicit monitor when the object's ‘synchronized’ method is invoked • Once an object is in the monitor, the monitor makes sure that no other thread accesses the same object 10
  • 11. Locking of an object Contd . . . • Monitor is implemented in Java through ‘synchronized’ keyword • The ‘synchronized’ keyword can be used in two ways: 1. Prefixed to the header of the method definition 2. Can synchronize the object of which the method is a member of • synchronized (<object>) { //statements to be synchronized } 11
  • 12. First Approach : synchronized Use of synchronized keyword class TwoStrings { synchronized static void print(String str1, String str2) { System.out.print(str1); try { Thread.sleep(500); }catch(InterruptedException ie) { } System.out.println(str2); } } 12
  • 13. Contd . . . First Approach : synchronized class PrintStringsThread implements Runnable { Thread thread; String str1, str2; PrintStringsThread(String str1,String str2) { this.str1 = str1; this.str2 = str2; thread = new Thread(this); thread.start(); } public void run() { TwoStrings.print(str1, str2); } } Shared Resource 13
  • 14. Contd . . . First Approach : synchronized class TestThread { public static void main(String args[]) { new PrintStringsThread("Hello ", "there."); new PrintStringsThread("How are ", "you?"); new PrintStringsThread("Thank you ", "very much!"); } Output } Got the output as expected 14
  • 15. Second Approach : synchronized class TwoStrings { static void print(String str1, String str2) { System.out.print(str1); try { Thread.sleep(500); }catch(InterruptedException ie){ } System.out.println(str2); } } class PrintStringsThread implements Runnable { Thread thread; String str1, str2; TwoStrings ts; 15
  • 16. Second Approach : synchronized Contd . . . PrintStringsThread(String str1, String str2, TwoStrings ts) { this.str1 = str1; this.str2 = str2; this.ts = ts; thread = new Thread(this); thread.start(); } Use of synchronized statement public void run() { synchronized (ts) { ts.print(str1, str2); } } } 16
  • 17. Contd . . . Second Approach : synchronized class TestThread { public static void main(String args[]) { new PrintStringsThread("Hello ", "there."); new PrintStringsThread("How are ", "you?"); new PrintStringsThread("Thank you ", "very much!"); } } Output Got the output as expected 17
  • 18. Summary • In this class we have discussed • Problem of synchronization • Monitors and locking objects • Two approaches of using synchronized keyword • Relevant example programs • In the next lesson we look at Inter-Thread Communication 18
  • 19. Quiz 1. Which concept is used by Java in inter-thread- synchronization A. Process B. Monitor C. Multitasking D. None 19
  • 20. Quiz Contd.. 2. Which keyword is used for synchronization in Java ? A. synchronize B. synchronised C. synchronized D. synchronizing 20
  • 21. Frequently Asked Questions 1. Explain the concept of synchronization 2. What is monitor? 3. How monitor is implemented in Java? 4. What are the different ways of using ‘synchronized’ keyword ? 21