Graphical interface application and deadlock problem of Java concurrent programming

Source: Internet
Author: User

I don't know why this book is about an interface application, Java interface is bad, inefficient, and the interface is the weakness of Java, probably because there is some knowledge of concurrent programming.

Why the GUI is single-threaded

Both swing and AWT are single-threaded. But it's not limited to Java, where GUI frameworks in Qt,nexistep,macos CoCoa X windows and other environments are single-threaded, and many people have tried to write multithreaded GUI frameworks, Eventually, however, the stability problems caused by race conditions and deadlocks are returned to the single-threaded event queue model: A dedicated thread extracts events from the queue and forwards them to the application-defined event handler.

These problems occur mainly in deadlocks caused by lock order problems:

For example: Modify the background color of the program:

The order is that the application makes modifications to the background Request ———— component Class ———— the operating system to draw.

The operating system then draws the component Class ———— component Class ———— refreshes the application interface.

Another aspect is to ensure that each object is thread-safe, resulting in a deadlock in which the lock sequence is inconsistent.

About the interface application to write so much, because it is not practical to think that this is very useful, know that the above knowledge can be in the development of the GUI framework of the time to go a lot less detours.

Avoid the danger of being active

Security and activity are relative, and we use the lock mechanism to ensure thread safety, but also because of the deadlock and other causes of active issues


dead Lock

There is a typical philosopher's meal question used to describe a deadlock.

5 Philosophers sitting on a table, only 5 chopsticks on the table, they eat to use a pair of chopsticks, they sometimes think, sometimes eat, when a thinking, he next to the people can eat, the following deadlock phenomenon is that each of them quickly grabbed the chopsticks on the left, and everyone is waiting for the right chopsticks, However, none of them had eaten, so no one would put down the chopsticks, so it was a deadlock.


The monitoring of deadlocks and recovery from deadlocks are considered in the design of the database system. In executing a transaction, if a deadlock occurs on a transaction, then it aborts the transaction, then executes the other, and then comes back and executes the transaction that was just discarded when the other transaction was completed.


However, the JVM does not have this system, and these threads will never be used when a set of Java threads are deadlocked. Depending on the work of the thread, the application may stop completely. The only solution is to restart.

Line sequence deadlock

To give a very simple chestnut: haha thought a lot of ways to let this lock can be locked, is to enlarge the acquisition time between two objects.

public class Leftrightdeallock {Private Final object right = new Object ();p rivate Final Object left = new Object ();p ublic void LeftRight () {synchronized (left) {try {Thread.Sleep (+)} catch (Interruptedexception e) {//TODO auto-generated Cat CH Blocke.printstacktrace ();} Synchronized (right) {dosomething ();}}} public void Rightleft () {synchronized (right) {try {Thread.Sleep (+)} catch (Interruptedexception e) {//TODO Auto-gener Ated catch Blocke.printstacktrace ();} Synchronized (left) {dosomething ();}}} private void DoSomething () {//TODO auto-generated method stubfor (int i = 0; i <; i++) {System.out.println ("Dosome Thing "+ i);}} public static void Main (string[] args) {final Leftrightdeallock lrdl = new Leftrightdeallock (); New Thread (New Runnable () { @Overridepublic void Run () {//TODO auto-generated method Stublrdl.leftright ();}}). Start (); New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stublrdl. Rightleft ();}}). Start ();}}

Dynamic Lock Sequence Deadlock

Take the transfer operation as an example

public void TransferMoney (account formaccaount, account Toaccount,dollaramount amount) {synchronized (Formaccaount) { Synchronized (Toaccount) {if (Formaccaount.getBalance.compareTo (amount) < 0) {throw new Insufficientfundsexcetion () ;} else {fromaccount.debit (amount); Toaccount.credit (amount);}}}
There seems to be no problem, and if two people transfer money to each other's account, then it becomes the rightleftdeadlock problem.


Solution: Through the lock sequence to avoid deadlocks, the answer Bell also need to ring people, since it is the lock sequence caused, then a fixed lock sequence can solve the problem.

public class Testlock {private static final object Tielock = new Object ();p the Rivate account fromacct;private account Toacct; public void TransferMoney (final account Fromacct, final account toacct,final Dollaramount amount) {This.fromacct = Fromacc T;this.toacct = Toacct;class Helper {public void transfer () {if (Fromacct.getbalance (). CompareTo (amount) < 0) {throw NE W insufficientfundsexcetion ();} else {fromacct.debit (amount); Toacct.credit (amount);}}} int fromhash = System.identityhashcode (FROMACCT); int tohash = System.identityhashcode (TOACCT); if (Fromhash < ToHash) {synchronized (FROMACCT) {synchronized (TOACCT) {new Helper (). Transfer ();}}} else if (Fromhash > Tohash) {synchronized (TOACCT) {synchronized (FROMACCT) {new Helper (). Transfer ();}}} else {Synchron Ized (Tielock) {synchronized (FROMACCT) {synchronized (TOACCT) {new Helper (). Transfer ();}}}} Private class Dollaramount {}private abstract class account {comparable<dollaramount> GetBalance () {return new Comp Arable<dollaRamount> () {@Overridepublic int compareTo (Dollaramount o) {//TODO auto-generated method Stubreturn 0;}};} abstract void Debit (Dollaramount a); abstract void Credit (Dollaramount a);}

A little change is guaranteed to be in eclipse without the Scarlet Letter. But the exception was not written. Mainly look at the code,

The System.identityhashcode method is to get the result of the hashcode inside the object. In rare cases, two objects may have the same hash value. Use extra-overtime locks. This extra lock is obtained before two account locks are obtained. This ensures that only one thread obtains the two locks in an unknown order at a time.














Graphical interface application and deadlock problem of Java concurrent programming

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.