"Java Synchronization block"

Source: Internet
Author: User
Tags instance method

original linkJakob Jenkov Translator: Li Tongjie javathe synchronization block (synchronized block) is used to mark methods or blocks of code that are synchronized. Javasynchronization blocks are used to avoid competition. This article describes the following:
    • Java Sync keyword (synchronzied)
    • Instance method synchronization
    • static method Synchronization
    • Synchronizing blocks in instance methods
    • Synchronous blocks in static methods
    • Java Synchronization Example

Java sync keyword (synchronized)

Synchronization blocks in Java are marked with synchronized. Synchronization blocks are synchronized on an object in Java. All synchronized blocks that are synchronized on an object can only be entered by one thread at a time and perform operations. All other threads waiting to enter the synchronization block will be blocked until the thread that executes the synchronization block exits.

There are four different types of synchronization blocks:

    • Instance method
    • Static methods
    • Synchronization blocks in an instance method
    • Synchronization blocks in a static method

The above synchronization blocks are synchronized on different objects. The actual need for that synchronization block depends on the specific situation.

Instance method synchronization

The following is a synchronous instance method:

    1. Public synchronized void Add (int value) {
    2. This.count + = value;
    3. }
Copy Code

Note the Synchronize (synchronized) keyword in the method declaration. This tells Java that the method is synchronous.

The Java instance method synchronization is synchronous on the object that owns the method. In this way, each instance's method synchronization is synchronized on a different object, that is, the instance to which the method belongs. Only one thread can run in the instance method synchronization block. If more than one instance exists, a thread can perform operations in one instance synchronization block at a time. One instance of a thread.

static method Synchronization

Static method synchronization, like the instance method synchronization method, also uses the Synchronized keyword. The Java static method synchronizes the following example:

    1. public static synchronized void Add (int value) {
    2. Count + = value;
    3. }
Copy Code

Again, the Synchronized keyword here tells Java that this method is synchronous.

Synchronization of static methods refers to synchronizing on the class object on which the method resides. Because a class can only correspond to one class object in a Java virtual machine, it allows only one thread to execute a static synchronization method in the same class.

For static synchronization methods in different classes, a thread can execute a static synchronization method in each class without waiting. A class can be executed by only one thread at a time, regardless of whether the static synchronization method in the class is called.

Synchronization blocks in an instance method

Sometimes you don't need to synchronize the entire method, but rather part of the synchronization method. Java can synchronize part of a method.

The example of a synchronization block in a non-synchronized Java method is as follows:

    1. public void Add (int value) {
    2. Synchronized (this) {
    3. This.count + = value;
    4. }
    5. }
Copy Code

The example uses the Java synchronization block builder to mark a piece of code as synchronous. The code is executed at the same time as the synchronization method.

Note the Java synchronization block constructor encloses the object with parentheses. In the example above, "This" is used, which is called the instance itself of the Add method. Objects enclosed in parentheses in the synchronization constructor are called Monitor objects. The code above uses the monitor object to synchronize, and the synchronous instance method uses the instance of the calling method itself as the monitor object.

Only one thread at a time can execute within a Java method synchronized to the same monitor object.

The following two examples all synchronize the instance objects they invoke, so they are equivalent to the execution effect of the synchronization.

    1. public class MyClass {
    2. Public synchronized void Log1 (string msg1, String msg2) {
    3. Log.writeln (MSG1);
    4. Log.writeln (MSG2);
    5. }
    6. public void log2 (string msg1, String msg2) {
    7. Synchronized (this) {
    8. Log.writeln (MSG1);
    9. Log.writeln (MSG2);
    10. }
    11. }
    12. }
Copy Code

In the example above, only one thread can execute within any one of the two synchronization blocks at a time.

If the second synchronization block is not synchronized on the this instance object, then two methods can be executed concurrently by the thread.

Synchronization blocks in a static method

Similar to the above, here are two examples of static method synchronization. These methods are synchronized on the class object to which the method belongs.

    1. public class MyClass {
    2. public static synchronized void Log1 (string msg1, String msg2) {
    3. Log.writeln (MSG1);
    4. Log.writeln (MSG2);
    5. }
    6. public static void Log2 (String msg1, String msg2) {
    7. Synchronized (Myclass.class) {
    8. Log.writeln (MSG1);
    9. Log.writeln (MSG2);
    10. }
    11. }
    12. }
Copy Code

These two methods do not allow simultaneous access by threads.

If the second synchronization block is not synchronized on the Myclass.class object. Then both methods can be accessed by the thread at the same time.

Java Synchronization Instance

In the following example, two threads are started, and the Add method that counter a similar instance is called. Because synchronization is on the instance to which the method belongs, only one thread can access the method at a time.

  1. public class counter{
  2. Long Count = 0;
  3. Public synchronized void Add (Long value) {
  4. This.count + = value;
  5. }
  6. }
  7. public class Counterthread extends thread{
  8. protected Counter Counter = null;
  9. Public Counterthread (Counter Counter) {
  10. This.counter = counter;
  11. }
  12. public void Run () {
  13. for (int i=0; i<10; i++) {
  14. Counter.add (i);
  15. }
  16. }
  17. }
  18. public class Example {
  19. public static void Main (string[] args) {
  20. Counter Counter = new Counter ();
  21. Thread Threada = new Counterthread (counter);
  22. Thread threadb = new Counterthread (counter);
  23. Threada.start ();
  24. Threadb.start ();
  25. }
  26. }
Copy Code

Two threads were created. Their constructors refer to the same counter instance. The Counter.add method is synchronous on the instance, because the Add method is an instance method and is tagged with the synchronized keyword. Therefore, only one thread is allowed to call the method at a time. Another thread must wait until the first thread exits the Add () method to continue executing the method.

If two threads refer to two different counter instances, they can call the Add () method at the same time. These methods invoke different objects, so these methods are also synchronized on different objects. These method calls will not be blocked. As shown in the following example:

    1. public class Example {
    2. public static void Main (string[] args) {
    3. Counter Countera = new Counter ();
    4. Counter Counterb = new Counter ();
    5. Thread Threada = new Counterthread (Countera);
    6. Thread threadb = new Counterthread (counterb);
    7. Threada.start ();
    8. Threadb.start ();
    9. }
    10. }
Copy CodeNote that these two threads, Threada and threadb, no longer reference the same counter instance. The add methods of Countera and Counterb are synchronized on the object to which they belong. Calling Countera's Add method will not block the Add method that calls Counterb.

"Java Synchronization block"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.