How Java implements a future

Source: Internet
Author: User

Implementing the Futrue Interface

public class Msgfuture<v> implements java.util.concurrent.future<v> {    ...    ...}    

  

The main features of the future are Future.get (),

  Get ()
Get (long timeout, timeunit unit)

The main ideas are as follows:
When constructing msgfuture, set the start time, here is sendtime; set timeout, default get () method time-out, our program can't wait indefinitely
The default get () corresponding value range is result, which defaults to a null object that identifies no return data

The value of result requires other threads to write values to the future object after completing the task, exposing a method Setresult (object)
    /**     * Set result value results, wake condition {@link #get (long, Timeunit)}     * @param result */public    synchronized void Setresult (Object result) {        reentrantlock.lock ();        try {            This.result = result;            Condition.signalall ();        } finally {            reentrantlock.unlock ();        }    }

Using Reentrantlock for data visibility control

Condition.signalall () can wake up the condition.await blocking wait

As for how other threads call to the Setresult (object) method, you can use Concurrenthashmap,key as MsgId, a value of Msgfuture object, set to a global, or two threads accessible, Other threads get to msgfuture based on MsgId, and then call the Setresult (object) method

    /** * Gets the result and throws TimeoutException * @param timeout * @param unit * @return * If the timeout has not been reached @thro WS interruptedexception * @throws timeoutexception */@SuppressWarnings ("all") public V get (long timeout, Ti                      Meunit unit) throws Interruptedexception, timeoutexception {Long left = Getlefttime (timeout, unit);                                            Get the rest of the world if (left < 0) {//There is no time left if (IsDone ()) {) According to the timeout configuration            If it is completed, return the result directly (V) This.result;            }else{//timeout throw new TimeoutException ("Return timeout, subsequent response will be discarded abort");                                    }}else{Reentrantlock.lock ();                                        Synchronize try {//Get lock first to determine if it is done, to prevent meaningless await if (IsDone ()) {                           First determine if the return (V) This.result has been completed;             Direct return     } logger.debug ("await" +left+ "MS");       Condition.await (Getlefttime (timeout, unit), timeunit.milliseconds);            No return, blocking wait, if condition is awakened, will also exit}finally {Reentrantlock.unlock () earlier; if (IsDone ()) {//was awakened or the time-out has expired, try to determine whether to complete return (V) this.                               Result                return} throw new TimeoutException ("No results obtained"); Timeout}}

  

    public Boolean IsDone () {        return this.result! = NULL;    }

  



All code
public class Msgfuture<v> implements java.util.concurrent.future<v> {private final static Logger Logger =    Loggerfactory.getlogger (Msgfuture.class);    /** * Global Empty object, if the future obtains a value, then it must not be null */private Final static object NULL = new Object ();    /** * Master Lock */private final Reentrantlock Reentrantlock = new Reentrantlock (); /** * condition, using its condition.await (left, timeunit.milliseconds) and Notifyall methods to implement blocking, wakeup */private final Condition Condit    Ion = Reentrantlock.newcondition ();    private int timeout;    Private volatile Object result = NULL;    Private long sendtime;        public msgfuture (int timeout, long sendtime) {this.timeout = timeout;    This.sendtime = Sendtime;    The public boolean cancel (Boolean mayinterruptifrunning) {return false;    } public boolean iscancelled () {return false;    } public boolean IsDone () {return this.result! = NULL; }/** * Get future results * @return * @throws InteRruptedexception */Public V get () throws Interruptedexception {Logger.debug ("sendtime:{}", Sendtime);        try {return get (timeout, timeunit.milliseconds);        } catch (TimeoutException e) {logger.error ("Get Future result exception", e);    } return null; /** * Gets the result and throws TimeoutException * @param timeout * @param unit * @return * If the timeout has not been reached @thr oWS interruptedexception * @throws timeoutexception * * @SuppressWarnings ("all") public V get (long timeout, T        Imeunit unit) throws Interruptedexception, timeoutexception {Long left = Getlefttime (timeout, unit);            if (left < 0) {//There is no time remaining if (IsDone ()) {return (V) This.result;            }else{//timeout throw new TimeoutException ("Return timeout, subsequent response will be discarded abort");            }}else{Reentrantlock.lock ();          try {//acquire the lock first to determine if it has been completed to prevent meaningless await      if (IsDone ()) {return (V) This.result;                } logger.debug ("await" +left+ "MS");            Condition.await (Getlefttime (timeout, unit), timeunit.milliseconds);            }finally {reentrantlock.unlock ();            } if (IsDone ()) {return (V) This.result;        } throw new TimeoutException ("No results obtained");  }}/** * Set result value, Wake condition {@link #get (long, Timeunit)} * @param result */public synchronized        void Setresult (Object result) {Reentrantlock.lock ();            try {this.result = result;        Condition.signalall ();        }finally {reentrantlock.unlock (); }}/** * Calculates the remaining time * @param timeout * @param unit * @return */Private long getlefttime (long ti        Meout, Timeunit unit) {Long now = System.currenttimemillis (); Timeout = Unit.tomillis (timeout); Convert to milliseconds return timeOut-(now-sendtime); }/*public static void Main (string[] args) {msgfuture msgfuture = new Msgfuture (2000,system.currenttimemillis ()        );        Test first wake, after get is normal Msgfuture.setresult ("Yoxi");        try {System.out.println (Msgfuture.get (2000,timeunit.milliseconds));        } catch (Interruptedexception e) {logger.error ("Interrupt exception", e);        } catch (TimeoutException e) {logger.error ("Test wake first, get error after", E); }    }*/}

  





How Java implements a future

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.