Wayne
Wayne

Reputation: 149

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?

Upvotes: 0

Views: 1971

Answers (1)

daveb
daveb

Reputation: 76221

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

Upvotes: 3

Related Questions