Java Timeout Control __java

Source: Internet
Author: User
Tags sessions thread class

Timeout control is a function that we can easily ignore in the system and can't be neglected. On the one hand, timeout is not the main business function of our system, most of the timeout control has been implemented by virtual machines or servers; On the other hand, timeout control is a necessary recessive function of many business, imagine, a Web application if in 10 seconds after the default timeout before responding, customers can endure it.

This article mainly summarizes some common timeout processing mechanisms, as well as the applicable scenarios.

First of all, put forward here a practical problem, we can think how to solve. A timeout is required to invoke the CORBA connection server and fetch data in order to give the user a good user experience (e.g. Service.handshake (), the process of shaking the handshake is the process of initiating a CORBA request), but unfortunately, The code generated by CORBA does not provide a parameter entry for the timeout (checked, it seems that the connection to set timeout in CORBA must be configured with his policy, but I do not know about it), in this case, how to use our known methods to complete the task.

In fact, the basic idea of this problem is related to the thread, because timeout means blocking, if only the main thread, then blocking means lost control, basically not timeout control (personally think that the thread running the middle of the way to judge and jump out of the loop is only the method of threading, not timeout control). If you have a master-slave two thread, it is up to us to know that the thread timed out and terminated it from the thread blocking process. The ultimate idea is to turn the other timeout problem into a line blocks until those problem.

Let's look at the first way, the common way to join on the Internet. Because there is no direct threading method to provide time-out parameters, you can convert the mind to join with a method that already provides a time-out. A join is a method of the thread class, meaning that the current thread waits for the calling thread to end, and most importantly, the join can pass in the parameters of the timeout control, referring to the following two prototypes:

Join (Long Millis) 
Then whether you can complete the pending timeout task in a child thread, join a child thread, return to the main thread when the join times out, and then terminate the child thread in the main thread. This is the way Timeoutcontroller is used in httpclient. Here the task is a child thread that completes tasks like a CORBA connection, and after the task join, the current running thread waits for the task to run and waits only for timeout time, if the timeout thread is still not finished, The main thread can live and break the child thread.

public static void Execute (Thread task, long timeout) throws TimeoutException {

        task.start ();

        try {

       task.join (timeout);

        } catch (Interruptedexception e) {/

       * If somebody interrupts us he knows
what the He is doing */

        }

        if (Task.isalive ()) {

       task.interrupt ();

       throw new TimeoutException ();

        }

    
The first way is not so intuitive, relatively speaking, join some detours, there is no more direct point of the way. That is, with the future,future of the concurrent package, there is a timeout parameter when the result is computed, which can be used to effectively timeout

Executorservice executor = Executors.newsinglethreadexecutor ();
   futuretask<licenseservice> future = new Futuretask<licenseservice> (
         new Callable<licenseservice > () {public
                              LicenseService call () {
                                    Licenseserveradapter adapter = new Licenseserveradapter (
                                                info);
                                    LicenseService service = Adapter.getlicenseservice ();
                                    Service.handshake ();
                                    return service;
                              }
                        );
   Executor.execute (future);
   return Future.get (Timeout * 1000, timeunit.milliseconds);

When it comes time to timeout, there is another scenario where the timeout is a session timeout for the Web server. You can imagine that if you implement the Web server, you need to implement the session function, then how to implement the session timeout. This problem can be solved in many ways, there are two, the first is in each session object to save a timestamp, each visit first check whether it has expired, such as expired, then recycle the session, if not expired, then update the timestamp, but there is a disadvantage, if not again after the expiration of the visit, Session will never be recycled, of course, here can be improved, such as every visit to check the expiration of all sessions, but also bring efficiency problems, interested friends can think about. Another way is the implementation of Tomcat, that is, a background thread on the session to do a scan, during the scanning process to implement the time stamp update or recycling issues, see Code
public void Backgroundprocess () {count = (count + 1)% Processexpiresfrequency;
    if (count = = 0) processexpires ();
     /** * Invalidate All sessions that have expired.
        */public void Processexpires () {Long timenow = System.currenttimemillis ();
        Session sessions[] = Findsessions ();
        
        int expirehere = 0; if (log.isdebugenabled ()) log.debug ("Start expire Sessions" + getName () + "at" + TimeNow + "Sessioncount"
        + sessions.length);
                for (int i = 0; i < sessions.length i++) {if (Sessions[i]!=null &&!sessions[i].isvalid ()) {
            expirehere++;
        } Long Timeend = System.currenttimemillis (); if (log.isdebugenabled ()) Log.debug ("End expire Sessions" + getName () + "Processingtime" + (timeend-timen
        ow) + "Expired sessions:" + Expirehere);

    Processingtime + = (timeend-timenow); }

The last topic on timeout is also interesting, in Linux, the C function of the API Connect method is not provided timeout parameters, as follows:

int connect (int sockfd,struct sockaddr * serv_addr,int addrlen);
So how does Java provide the Connect API with parameters through the packaging of the native method? In fact, the idea here is consistent with the previous, that is, to find an alternative to have the time-out parameter method. The first is to set connect as non-blocking, then call Connect and return immediately, and finally register the write event to the poll with timeout.
* * To doing a timed connect we make the socket non-blocking * and poll with a timeout;
    */if (Attachtimeout > 0) {dbgsysconfigureblocking (socketfd, Jni_false);
    Err = Dbgsysconnect (socketfd, struct sockaddr *) &sa, sizeof (SA)); if (err = = dbg_einprogress && attachtimeout > 0) {err = Dbgsysfinishconnect (SOCKETFD, (long) attachtime

        Out);
            if (err = = Dbg_etimeout) {dbgsysconfigureblocking (socketfd, jni_true);
        Return_error (Jdwptransport_error_timeout, "Connect timed out");
    } int dbgsysfinishconnect (int fd, long timeout) {int RV = dbgsyspoll (fd, 0, 1, timeout);
    if (rv = = 0) {return dbg_etimeout;
    if (rv > 0) {return 0;
return RV;
    int dbgsyspoll (int fd, Jboolean Rd, Jboolean WR, long timeout) {struct POLLFD fds[1];

    int RV;
    FDS[0].FD = FD;
    fds[0].events = 0;
    if (RD) {fds[0].events |= pollin;
 }   if (WR) {fds[0].events |= pollout;

    } fds[0].revents = 0;
    RV = Poll (&fds[0], 1, timeout);
        if (rv >= 0) {rv = 0;
        if (Fds[0].revents & Pollin) {RV |= Dbg_pollin;
        } if (Fds[0].revents & pollout) {RV |= dbg_pollout;
} return to RV;

 }

Reference articles:

Http://blog.donews.com/maverick/archive/2005/08/10/502286.aspx

http://my.oschina.net/astute/blog/92339


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.