简体   繁体   中英

How do I handle a callback in java

I have a servlet that request a geolocation from another server using an http get. The response is received via a callback from the other server and ends up in another servlet. Ideally I would like to return a map on the first servlet and make this asynchronous mechanism synchronous. All I can come up with at the moment is to poll a shared hashmap till the value is there, it seems like a bit of an ugly hack. Any ideas how I can implement this more elegantly?

At the most basic level, using a condition variable is more efficient than a non-blocking loop.

// global, shared lock.
final Lock lock = new ReentrantLock();
final Condition locationReceived  = lock.newCondition(); 

// first servlet:
//
lock.lock();
try {
    requestLocation();
    if (!locationReceived.await(10, TimeUnit.SECONDS)) {
        // location was not received in the timeout.
    } else {
        // read location from shared object.
    }
} finally {
    lock.unlock();
}


// servlet that receives geolocation
//
lock.lock();
try {
    // set location in shared object.
    locationReceived.signal();
} finally {
    lock.unlock();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM