java中如何处理回调

发布于 2024-10-06 23:08:08 字数 176 浏览 0 评论 0原文

我有一个 servlet,它使用 http get 从另一台服务器请求地理位置。响应是通过来自其他服务器的回调接收的,并最终到达另一个 servlet。理想情况下,我想在第一个 servlet 上返回一个映射,并使这个异步机制同步。目前我能想到的就是轮询共享哈希图,直到值存在为止,这看起来有点丑陋。我有什么想法可以更优雅地实现这一点吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别再吹冷风 2024-10-13 23:08:08

在最基本的层面上,使用条件变量比非阻塞循环更有效。

// 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();
}

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文