简体   繁体   English

如何处理Java中的回调

[英]How do I handle a callback in java

I have a servlet that request a geolocation from another server using an http get. 我有一个servlet,它使用http get从另一个服务器请求地理位置。 The response is received via a callback from the other server and ends up in another servlet. 响应是通过另一个服务器的回调接收的,并最终到达另一个servlet。 Ideally I would like to return a map on the first servlet and make this asynchronous mechanism synchronous. 理想情况下,我想在第一个servlet上返回一个映射,并使该异步机制同步。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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