开发者

How do I handle a callback in java

开发者 https://www.devze.com 2023-01-29 09:48 出处:网络
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

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. 开发者_JAVA百科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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消