001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to you under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.hadoop.hbase.client;
018
019import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
020
021/**
022 * Tracks the amount of time remaining for an operation.
023 */
024class RetryingTimeTracker {
025  private long globalStartTime = -1;
026
027  public RetryingTimeTracker start() {
028    if (this.globalStartTime < 0) {
029      this.globalStartTime = EnvironmentEdgeManager.currentTime();
030    }
031    return this;
032  }
033
034  public int getRemainingTime(int callTimeout) {
035    if (callTimeout <= 0) {
036      return 0;
037    } else {
038      if (callTimeout == Integer.MAX_VALUE) {
039        return Integer.MAX_VALUE;
040      }
041      long remaining = EnvironmentEdgeManager.currentTime() - this.globalStartTime;
042      long remainingTime = callTimeout - remaining;
043      if (remainingTime < 1) {
044        // If there is no time left, we're trying anyway. It's too late.
045        // 0 means no timeout, and it's not the intent here. So we secure both cases by
046        // resetting to the minimum.
047        remainingTime = 1;
048      }
049      if (remainingTime > Integer.MAX_VALUE) {
050        throw new RuntimeException("remainingTime=" + remainingTime +
051            " which is > Integer.MAX_VALUE");
052      }
053      return (int)remainingTime;
054    }
055  }
056
057  public long getStartTime() {
058    return this.globalStartTime;
059  }
060}