Java Thread Third edition third chapter data synchronization reading notes

Source: Internet
Author: User


Sharing data issues between multiple threads
First, SynchronizedkeywordThe word atomic is not related to "atoms", it was previously thought to be the smallest unit of matter and could no longer be disassembled into smaller parts. When a method is declared as synchronized, the thread that executes this method must first obtain a token, which we call a lock.

Once the method obtains (or is acquired) a lock, it executes this method and then releases (or returns) the lock. The lock is freed regardless of how the method is returned (including through exceptions).
Second, the Volatilekeyword hypothesis variable is marked as volatile. Each time the variable is used, it must be read from the main register. In the same way. Each time the variable is written, the value must be stored in the primary register. Further. java specifies that the load and storage of volatile variables is atomic. Whether it is a long or a double variable.

Volatile declaration of variables for + + 、--operation does not guarantee atomicity.

An array of

     volatile declarations makes the reference to an array an element in a volatile array, not volatile.
Iii. discussion on many other race conditions

public class Scorelabel extends JLabel implements Characterlistener {private volatile int score = 0;    private int char2type =-1;    Private Charactersource generator = null, typist = NULL;        Public Scorelabel (Charactersource generator, Charactersource typist) {this.generator = generator;        This.typist = typist;        if (generator! = null) Generator.addcharacterlistener (this);           if (typist! = null) Typist.addcharacterlistener (this);    Public Scorelabel () {This (null, NULL); } public synchronized void Resetgenerator (Charactersource newgenerator) {if (generator! = NULL) gene        Rator.removecharacterlistener (this);        Generator = Newgenerator;            if (generator! = null) Generator.addcharacterlistener (this); } public synchronized void Resettypist (Charactersource newtypist) {if (typist! = null) typist.remove        Characterlistener (this); Typist = Newtypist;    if (typist! = null) Typist.addcharacterlistener (this);        } public synchronized void Resetscore () {score = 0;        Char2type =-1;    SetScore (); } private void SetScore () {//This method is explained later in Chapter 7 Swingutilities.invokelate            R (New Runnable () {public void run () {SetText (integer.tostring (score));    }        });  } public synchronized void Newcharacter (characterevent CE) {//Previous character not typed correctly-1 point                Penalty if (Ce.source = = Generator) {if (Char2type! =-1) {score--;            SetScore ();        } char2type = Ce.character; }//If character is extraneous-1 point penalty//If character does does match-1 point penalty el           Se {if (char2type! = ce.character) {score--;        } else {score++;       Char2type =-1;       } setscore (); }    } }


Such shared data consists of the actual number of scores, the letters that need to be entered, and the number of letters held by the minority to be used as variables for registration.     Solving race condition problems means that the data is synchronized in the correct scope. Assume that the Newcharacter method does not ensure synchronization. The changes of variables Char2type and score variables are not guaranteed to get the correct last change value in real-time in all threads, resulting in char2type-based inference failure and successive score failures.

The solution is that all of these variables in this class involve the current class as a synchronous lock (that is, each method joins a Synchronizedkeyword). The goal is to call these methods in all threads must be mutually exclusive operations, it is not possible to invoke multiple threads at the same time to manipulate the methods of these two variables, so as to ensure correctness.

Four, display lock

public class Scorelabel extends JLabel implements Characterlistener {private volatile int score = 0;    private int char2type =-1;    Private Charactersource generator = null, typist = NULL;    Private Lock Scorelock = new Reentrantlock ();        Public Scorelabel (Charactersource generator, Charactersource typist) {this.generator = generator;        This.typist = typist;        if (generator! = null) Generator.addcharacterlistener (this);           if (typist! = null) Typist.addcharacterlistener (this);    Public Scorelabel () {This (null, NULL);            } public void Resetgenerator (Charactersource newgenerator) {try {scorelock.lock ();            if (generator! = null) Generator.removecharacterlistener (this);            Generator = Newgenerator;        if (generator! = null) Generator.addcharacterlistener (this);        } finally {Scorelock.unlock (); }} public void Resettypist (Charactersource newtypist) {try {scorelock.lock ();            if (typist! = null) Typist.removecharacterlistener (this);            typist = Newtypist;        if (typist! = null) Typist.addcharacterlistener (this);        } finally {Scorelock.unlock ();            }} public void Resetscore () {try {scorelock.lock ();            Score = 0;            Char2type =-1;        SetScore ();        } finally {Scorelock.unlock (); }} private void SetScore () {//This method would be explained later in Chapter 7 Swingutilities.invok            Elater (New Runnable () {public void run () {SetText (integer.tostring (score));    }        });            } public void Newcharacter (characterevent CE) {try {scorelock.lock (); Previous character not typed correctly-1 point penalty if (Ce.source = = GenerAtor) {if (Char2type! =-1) {score--;                SetScore ();            } char2type = Ce.character;            }//If character is extraneous-1 point penalty//if character does not match-1 point penalty                else {if (char2type! = ce.character) {score--;                    } else {score++;                Char2type =-1;            } setscore ();        }} finally {Scorelock.unlock (); }    } }


Similar to the above example principle, are involved in Char2type, score two variables change the method to join the lock, the current sample is only the second syntax using the provided lock and unlock to lock the unlock operation, in this case, the two practices are equivalent. The difference between synchronized and lock is discussed later.
v. Lock Scope
public class Scorelabel extends JLabel implements Characterlistener {private volatile int score = 0;    private int char2type =-1;    Private Charactersource generator = null, typist = NULL;    Private Lock Scorelock = new Reentrantlock ();        Public Scorelabel (Charactersource generator, Charactersource typist) {this.generator = generator;        This.typist = typist;        if (generator! = null) Generator.addcharacterlistener (this);           if (typist! = null) Typist.addcharacterlistener (this);    Public Scorelabel () {This (null, NULL);            } public void Resetgenerator (Charactersource newgenerator) {try {scorelock.lock ();            if (generator! = null) Generator.removecharacterlistener (this);            Generator = Newgenerator;        if (generator! = null) Generator.addcharacterlistener (this);        } finally {Scorelock.unlock (); }} public void Resettypist (Charactersource newtypist) {try {scorelock.lock ();            if (typist! = null) Typist.removecharacterlistener (this);            typist = Newtypist;        if (typist! = null) Typist.addcharacterlistener (this);        } finally {Scorelock.unlock ();            }} public void Resetscore () {try {scorelock.lock ();            Score = 0;            Char2type =-1;        SetScore ();        } finally {Scorelock.unlock (); }} private void SetScore () {//This method would be explained later in Chapter 7 Swingutilities.invok            Elater (New Runnable () {public void run () {SetText (integer.tostring (score));    }        }); public void Newcharacter (characterevent CE) {if (Ce.source = = Generator) {try {SC                Orelock.lock (); Previous character not typed correctly-1 point penalty if (char2type! = 1) {score--;                SetScore ();            } char2type = Ce.character;            } finally {Scorelock.unlock ();        }}//If character is extraneous-1 point penalty//if character does not match-1 point penalty                else {try {scorelock.lock ();                if (char2type! = ce.character) {score--;                    } else {score++;                Char2type =-1;            } setscore ();            } finally {Scorelock.unlock (); }        }    } }



Lock and unlock can be placed wherever they are needed.
Six, synchronized block
public class Scorelabel extends JLabel implements Characterlistener {private volatile int score = 0;    private int char2type =-1;    Private Charactersource generator = null, typist = NULL;        Public Scorelabel (Charactersource generator, Charactersource typist) {this.generator = generator;        This.typist = typist;        if (generator! = null) Generator.addcharacterlistener (this);           if (typist! = null) Typist.addcharacterlistener (this);    Public Scorelabel () {This (null, NULL); } public synchronized void Resetgenerator (Charactersource newgenerator) {if (generator! = NULL) gene        Rator.removecharacterlistener (this);        Generator = Newgenerator;            if (generator! = null) Generator.addcharacterlistener (this); } public synchronized void Resettypist (Charactersource newtypist) {if (typist! = null) typist.remove        Characterlistener (this); Typist = Newtypist;    if (typist! = null) Typist.addcharacterlistener (this);        } public synchronized void Resetscore () {score = 0;        Char2type =-1;    SetScore (); } private void SetScore () {//This method is explained later in Chapter 7 Swingutilities.invokelate            R (New Runnable () {public void run () {SetText (integer.tostring (score));    }        });        } public void Newcharacter (characterevent CE) {//Previous character not typed correctly-1 point penalty                    if (Ce.source = = Generator) {synchronized (this) {if (Char2type! =-1) {                    score--;                SetScore ();            } char2type = Ce.character;        }}//If character is extraneous-1 point penalty//if character does not match-1 point penalty else {synchronized (this) {if (Char2type! = CE.character) {score--;                   } else {score++;               Char2type =-1;            } setscore (); }        }    } }



In this example, the object that is locked is the same object that is used to synchronize the method: the This object.
Vii. selection of locking mechanismSynchronized differs from lock on static methods, because using synchronized on a method is locked for the current object. While static methods are global, using this approach makes it difficult to ensure correctness, instead using lock because it is not related to the current object. It is only necessary to set lock and unlock within the method so it is easier to ensure the correctness of multithreaded synchronization.
VIII. Lock Interface
Boolean Trylock ()
The lock is acquired only if the Shi is called the spare state.
Assuming the lock is available, the lock is acquired and the value immediately returns TRUE.

Assume that the lock is not available. Then this method returns the value false immediately.

Typical usage statements for this method are as follows:

Lock lock = ...;
if (Lock.trylock ()) {
try {
Manipulate protected State
} finally {
Lock.unlock ();
}
} else {
Perform alternative actions
}
This method of use ensures that the lock is assumed to be acquired. The lock is released, assuming the lock is not acquired, you will not attempt to release it.



Return:
Returns true if the lock is acquired;




IX Nested Lock

public class Scorelabel extends JLabel implements Characterlistener {private volatile int score = 0;    private int char2type =-1;    Private Charactersource generator = null, typist = NULL;        Public Scorelabel (Charactersource generator, Charactersource typist) {this.generator = generator;        This.typist = typist;        if (generator! = null) Generator.addcharacterlistener (this);           if (typist! = null) Typist.addcharacterlistener (this);    Public Scorelabel () {This (null, NULL); } public synchronized void Resetgenerator (Charactersource newgenerator) {if (generator! = NULL) gene        Rator.removecharacterlistener (this);        Generator = Newgenerator;            if (generator! = null) Generator.addcharacterlistener (this); } public synchronized void Resettypist (Charactersource newtypist) {if (typist! = null) typist.remove        Characterlistener (this); Typist = Newtypist;    if (typist! = null) Typist.addcharacterlistener (this);        } public synchronized void Resetscore () {score = 0;        Char2type =-1;    SetScore (); } private void SetScore () {//This method is explained later in Chapter 7 Swingutilities.invokelate            R (New Runnable () {public void run () {SetText (integer.tostring (score));    }        });            } private synchronized void newgeneratorcharacter (int c) {if (Char2type! =-1) {score--;        SetScore ();    } Char2type = C;        } private synchronized void newtypistcharacter (int c) {if (Char2type! = c) {score--;            } else {score++;        Char2type =-1;    } setscore ();  } public synchronized void Newcharacter (characterevent CE) {//Previous character not typed correctly-1 point Penalty if (Ce.source = = Generator) {NewgeneratorCharacter (Ce.character); }//If character is extraneous-1 point penalty//If character does does match-1 point penalty el        SE {newtypistcharacter (ce.character); }    } }



The synchronized lock is reentrant. That is, when the other synchronized methods of this class are called in the method that currently declares synchronized, it is possible to enter directly without acquiring the lock operation again.
public int Getholdcount ()query the number of times that the current thread has retained this lock.
for each lock operation that does not match the unlock operation. The thread will hold a lock.

Keep count information is usually used only for testing and commissioning. For example, suppose you should not use a lock that has been held to enter a part of the code. You can declare such as the following:

Class X {   reentrantlock lock = new Reentrantlock ();   // ...        public void M () {      assert lock.getholdcount () = = 0;     Lock.lock ();     try {       //... method body     } finally {       lock.unlock ();}}   }

return:
The number of times the current thread holds this lock, assuming that the lock has not been persisted by the current thread. Then returns 0
10. DeadlockA deadlock occurs when two or more thread waits for two or more two locks to be released. and the program's environment allows lock to never be released.
11. Lock Fair (fairness)How should lock be granted when using the clear lock? 1. Let lock should be granted on a first-come-first-served basis. 2. Let it be granted in the order in which it can serve the most requests. 3. The lock should be given in the most advantageous form of the system. No matter what it is used for. (Synchronized close to this)




Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Java Thread Third edition third chapter data synchronization reading notes

Related Article

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.