View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  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  package org.apache.hadoop.hbase.regionserver.compactions;
19  
20  import java.util.Calendar;
21  import java.util.GregorianCalendar;
22  import org.apache.hadoop.hbase.classification.InterfaceAudience;
23  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
24  
25  @InterfaceAudience.Private
26  public class CurrentHourProvider {
27  
28    private CurrentHourProvider() {
29      throw new AssertionError();
30    }
31  
32    private static final class Tick {
33      final int currentHour;
34      final long expirationTimeInMillis;
35  
36      Tick(int currentHour, long expirationTimeInMillis) {
37        this.currentHour = currentHour;
38        this.expirationTimeInMillis = expirationTimeInMillis;
39      }
40    }
41  
42    private static Tick nextTick() {
43      Calendar calendar = new GregorianCalendar();
44      calendar.setTimeInMillis(EnvironmentEdgeManager.currentTime());
45      int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
46      moveToNextHour(calendar);
47      return new Tick(currentHour, calendar.getTimeInMillis());
48    }
49  
50    private static void moveToNextHour(Calendar calendar) {
51      calendar.add(Calendar.HOUR_OF_DAY, 1);
52      calendar.set(Calendar.MINUTE, 0);
53      calendar.set(Calendar.SECOND, 0);
54      calendar.set(Calendar.MILLISECOND, 0);
55    }
56  
57    private static volatile Tick tick = nextTick();
58  
59    public static int getCurrentHour() {
60      Tick tick = CurrentHourProvider.tick;
61      if (EnvironmentEdgeManager.currentTime() < tick.expirationTimeInMillis) {
62        return tick.currentHour;
63      }
64      tick = nextTick();
65      CurrentHourProvider.tick = tick;
66      return tick.currentHour;
67    }
68  
69    //RestrictedApi - only to be called for tests
70    static void advanceTick() {
71      tick = nextTick();
72    }
73  }