Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface GeolocationListener {
- public void onResult(Address[] addresses);
- public void onError(Exception e);
- }
- public class SignGuestbookServlet extends HttpServlet {
- public void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
- // ...
- resp.sendRedirect("/guestbook.jsp");
- }
- }
- Response a = getResponse();
- // wait until the response is received, do not go further
- // process
- Response b = getResponse();
- // wait until the response is received, do not go further
- process(a,b);
- private Address getFullAddress (String text, AddressListener listener, ... ){
- // new Geolocation(text, listener, options).start()
- // implements Geolocation.GeolocationListener
- // how to return the Address from the onResult ?
- }
- import java.util.concurrent.*;
- public class MakeAsynchronousCodeSynchronous {
- public static void main(String[] args) throws Exception {
- final Listener listener = new Listener();
- Runnable delayedTask = new Runnable() {
- @Override
- public void run() {
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- throw new IllegalStateException("Shouldn't be interrupted", e);
- }
- listener.onResult(123);
- }
- };
- System.out.println(System.currentTimeMillis() + ": Starting task");
- Executors.newSingleThreadExecutor().submit(delayedTask);
- System.out.println(System.currentTimeMillis() + ": Waiting for task to finish");
- while (!listener.isDone()) {
- Thread.sleep(100);
- }
- System.out.println(System.currentTimeMillis() + ": Task finished; result=" + listener.getResult());
- }
- private static class Listener {
- private Integer result;
- private boolean done;
- public void onResult(Integer result) {
- this.result = result;
- this.done = true;
- }
- public boolean isDone() {
- return done;
- }
- public Integer getResult() {
- return result;
- }
- }
- }
- ExecutorService es = Executors.newFixedThreadPool(2);
- ...
- Future<Response> responseA = es.submit(responseGetter);
- Future<Response> responseB = es.submit(responseGetter);
- process(responseA.get(), responseB.get());
- CountDownLatch latch = new CountDownLatch(1);
- Response a = getResponse(latch);
- latch.await();
- latch = new CountDownLatch(1);
- Response b = getResponse(latch);
- latch.await();
- process(a, b);
- public Response getResponse(CountDownLatch latch) {
- someAsychBloc(final CountDownLatch latch) {
- do work
- latch.countDown();
- }
- }
Add Comment
Please, Sign In to add comment