Mode 4-balking

Source: Internet
Author: User

Refer to Java multithreading Design Mode

When the alert conditions are not met, they are immediately interrupted.

// If any data is modified, it will be stored in block security public synchronized void save () throws ioexception {If (! Changed) {system. Out. println (thread. currentthread (). getname () + "balks"); return ;}Dosave (); changed = false ;}
// If there is any data modification, store it in block security to delete the synchronized method, and extend the time to increase the chance of an error. Public void save () throws ioexception {If (! Changed) {system. out. println (thread. currentthread (). getname () + "balks"); return;} dosave (); try {thread. sleep (100);} catch (interruptedexception e) {}changed = false ;}

Result: Repeated writes exist.

SaverThread calls doSave, content = No.0ChangerThread balksSaverThread calls doSave, content = No.1ChangerThread balksChangerThread calls doSave, content = No.2SaverThread calls doSave, content = No.2ChangerThread balksChangerThread calls doSave, content = No.4SaverThread calls doSave, content = No.4ChangerThread balksChangerThread calls doSave, content = No.6SaverThread calls doSave, content = No.7ChangerThread balksChangerThread calls doSave, content = No.8SaverThread calls doSave, content = No.9ChangerThread balksChangerThread calls doSave, content = No.10
 
Set timeout. If the timeout time expires and the alert condition is not met, an exception is thrown:
 
private static final long TIMEOUT = 30000;
Public synchronized request getrequest () {long start = system. currenttimemillis (); // start time while (queue. Size () <= 0 ){Long Now = system. currenttimemillis (); // current time long rest = timeout-(now-Start); // remaining time if (rest <= 0) {Throw new livenessexception ("thrown by" + thread. currentthread (). getname ());}Try {Wait (rest);} catch (interruptedexception e) {}} return (request) queue. removefirst ();}

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.