001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.regionserver.compactions;
019
020import java.util.Calendar;
021import java.util.GregorianCalendar;
022
023import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
024import org.apache.yetus.audience.InterfaceAudience;
025import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
026
027@InterfaceAudience.Private
028public class CurrentHourProvider {
029  private CurrentHourProvider() { throw new AssertionError(); }
030
031  private static final class Tick {
032    final int currentHour;
033    final long expirationTimeInMillis;
034
035    Tick(int currentHour, long expirationTimeInMillis) {
036      this.currentHour = currentHour;
037      this.expirationTimeInMillis = expirationTimeInMillis;
038    }
039  }
040
041  @VisibleForTesting
042  static Tick nextTick() {
043    Calendar calendar = new GregorianCalendar();
044    calendar.setTimeInMillis(EnvironmentEdgeManager.currentTime());
045    int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
046    moveToNextHour(calendar);
047    return new Tick(currentHour, calendar.getTimeInMillis());
048  }
049
050  private static void moveToNextHour(Calendar calendar) {
051    calendar.add(Calendar.HOUR_OF_DAY, 1);
052    calendar.set(Calendar.MINUTE, 0);
053    calendar.set(Calendar.SECOND, 0);
054    calendar.set(Calendar.MILLISECOND, 0);
055  }
056
057  @VisibleForTesting
058  static volatile Tick tick = nextTick();
059
060  public static int getCurrentHour() {
061    Tick tick = CurrentHourProvider.tick;
062    if (EnvironmentEdgeManager.currentTime() < tick.expirationTimeInMillis) {
063      return tick.currentHour;
064    }
065
066    CurrentHourProvider.tick = tick = nextTick();
067    return tick.currentHour;
068  }
069}