Home | History | Annotate | Download | only in internal
      1 /*
      2  * Copyright (C) 2013 Square, Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.squareup.okhttp.internal;
     17 
     18 import com.squareup.okhttp.Route;
     19 import java.util.LinkedHashSet;
     20 import java.util.Set;
     21 
     22 /**
     23  * A blacklist of failed routes to avoid when creating a new connection to a
     24  * target address. This is used so that OkHttp can learn from its mistakes: if
     25  * there was a failure attempting to connect to a specific IP address or proxy
     26  * server, that failure is remembered and alternate routes are preferred.
     27  */
     28 public final class RouteDatabase {
     29   private final Set<Route> failedRoutes = new LinkedHashSet<>();
     30 
     31   /** Records a failure connecting to {@code failedRoute}. */
     32   public synchronized void failed(Route failedRoute) {
     33     failedRoutes.add(failedRoute);
     34   }
     35 
     36   /** Records success connecting to {@code failedRoute}. */
     37   public synchronized void connected(Route route) {
     38     failedRoutes.remove(route);
     39   }
     40 
     41   /** Returns true if {@code route} has failed recently and should be avoided. */
     42   public synchronized boolean shouldPostpone(Route route) {
     43     return failedRoutes.contains(route);
     44   }
     45 
     46   public synchronized int failedRoutesCount() {
     47     return failedRoutes.size();
     48   }
     49 }
     50