View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.client;
20  
21  import java.util.concurrent.TimeUnit;
22  import java.util.concurrent.TimeoutException;
23  import java.util.concurrent.atomic.AtomicReference;
24  
25  import org.eclipse.jetty.client.api.Request;
26  import org.eclipse.jetty.client.api.Response;
27  import org.eclipse.jetty.client.api.Result;
28  import org.eclipse.jetty.util.log.Log;
29  import org.eclipse.jetty.util.log.Logger;
30  import org.eclipse.jetty.util.thread.Scheduler;
31  
32  public class TimeoutCompleteListener implements Response.CompleteListener, Runnable
33  {
34      private static final Logger LOG = Log.getLogger(TimeoutCompleteListener.class);
35  
36      private final AtomicReference<Scheduler.Task> task = new AtomicReference<>();
37      private final Request request;
38  
39      public TimeoutCompleteListener(Request request)
40      {
41          this.request = request;
42      }
43  
44      @Override
45      public void onComplete(Result result)
46      {
47          Scheduler.Task task = this.task.getAndSet(null);
48          if (task != null)
49          {
50              boolean cancelled = task.cancel();
51              if (LOG.isDebugEnabled())
52                  LOG.debug("Cancelled (successfully: {}) timeout task {}", cancelled, task);
53          }
54      }
55  
56      public boolean schedule(Scheduler scheduler)
57      {
58          long timeout = request.getTimeout();
59          Scheduler.Task task = scheduler.schedule(this, timeout, TimeUnit.MILLISECONDS);
60          if (this.task.getAndSet(task) != null)
61              throw new IllegalStateException();
62          if (LOG.isDebugEnabled())
63              LOG.debug("Scheduled timeout task {} in {} ms for {}", task, timeout, request);
64          return true;
65      }
66  
67      @Override
68      public void run()
69      {
70          if (LOG.isDebugEnabled())
71              LOG.debug("Executing timeout task {} for {}", task, request);
72          request.abort(new TimeoutException("Total timeout elapsed"));
73      }
74  }