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