| 1 | /** |
| 2 | * |
| 3 | * Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com> |
| 4 | * |
| 5 | * ==================================================================== |
| 6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | * you may not use this file except in compliance with the License. |
| 8 | * You may obtain a copy of the License at |
| 9 | * |
| 10 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | * |
| 12 | * Unless required by applicable law or agreed to in writing, software |
| 13 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | * See the License for the specific language governing permissions and |
| 16 | * limitations under the License. |
| 17 | * ==================================================================== |
| 18 | */ |
| 19 | package org.jclouds.concurrent; |
| 20 | |
| 21 | import static com.google.common.base.Throwables.propagate; |
| 22 | |
| 23 | import java.util.concurrent.TimeoutException; |
| 24 | |
| 25 | import org.jclouds.util.Throwables2; |
| 26 | |
| 27 | import com.google.common.base.Supplier; |
| 28 | |
| 29 | /** |
| 30 | * |
| 31 | * @author Adrian Cole |
| 32 | */ |
| 33 | public class RetryOnTimeOutExceptionSupplier<T> implements Supplier<T> { |
| 34 | private final Supplier<T> delegate; |
| 35 | |
| 36 | public RetryOnTimeOutExceptionSupplier(Supplier<T> delegate) { |
| 37 | this.delegate = delegate; |
| 38 | } |
| 39 | |
| 40 | @Override |
| 41 | public T get() { |
| 42 | TimeoutException ex = null; |
| 43 | for (int i = 0; i < 3; i++) { |
| 44 | try { |
| 45 | ex = null; |
| 46 | return delegate.get(); |
| 47 | } catch (Exception e) { |
| 48 | if ((ex = Throwables2.getFirstThrowableOfType(e, TimeoutException.class)) != null) |
| 49 | continue; |
| 50 | propagate(e); |
| 51 | assert false; |
| 52 | return null; |
| 53 | } |
| 54 | } |
| 55 | if (ex != null) |
| 56 | propagate(ex); |
| 57 | assert false; |
| 58 | return null; |
| 59 | } |
| 60 | |
| 61 | @Override |
| 62 | public String toString() { |
| 63 | return "RetryOnTimeOutExceptionSupplier(" + delegate + ")"; |
| 64 | } |
| 65 | |
| 66 | } |