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;
025
026@InterfaceAudience.Private
027public class CurrentHourProvider {
028  private CurrentHourProvider() { throw new AssertionError(); }
029
030  private static final class Tick {
031    final int currentHour;
032    final long expirationTimeInMillis;
033
034    Tick(int currentHour, long expirationTimeInMillis) {
035      this.currentHour = currentHour;
036      this.expirationTimeInMillis = expirationTimeInMillis;
037    }
038  }
039
040  static Tick nextTick() {
041    Calendar calendar = new GregorianCalendar();
042    calendar.setTimeInMillis(EnvironmentEdgeManager.currentTime());
043    int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
044    moveToNextHour(calendar);
045    return new Tick(currentHour, calendar.getTimeInMillis());
046  }
047
048  private static void moveToNextHour(Calendar calendar) {
049    calendar.add(Calendar.HOUR_OF_DAY, 1);
050    calendar.set(Calendar.MINUTE, 0);
051    calendar.set(Calendar.SECOND, 0);
052    calendar.set(Calendar.MILLISECOND, 0);
053  }
054
055  static volatile Tick tick = nextTick();
056
057  public static int getCurrentHour() {
058    Tick tick = CurrentHourProvider.tick;
059    if (EnvironmentEdgeManager.currentTime() < tick.expirationTimeInMillis) {
060      return tick.currentHour;
061    }
062
063    CurrentHourProvider.tick = tick = nextTick();
064    return tick.currentHour;
065  }
066}