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  
23  import org.apache.hadoop.hbase.classification.InterfaceAudience;
24  
25  @InterfaceAudience.Private
26  public class CurrentHourProvider {
27    private CurrentHourProvider() { throw new AssertionError(); }
28  
29    private static final class Tick {
30      final int currentHour;
31      final long expirationTimeInMillis;
32  
33      Tick(int currentHour, long expirationTimeInMillis) {
34        this.currentHour = currentHour;
35        this.expirationTimeInMillis = expirationTimeInMillis;
36      }
37    }
38  
39    private static Tick nextTick() {
40      Calendar calendar = new GregorianCalendar();
41      int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
42      moveToNextHour(calendar);
43      return new Tick(currentHour, calendar.getTimeInMillis());
44    }
45  
46    private static void moveToNextHour(Calendar calendar) {
47      calendar.add(Calendar.HOUR_OF_DAY, 1);
48      calendar.set(Calendar.MINUTE, 0);
49      calendar.set(Calendar.SECOND, 0);
50      calendar.set(Calendar.MILLISECOND, 0);
51    }
52  
53    private static volatile Tick tick = nextTick();
54  
55    public static int getCurrentHour() {
56      Tick tick = CurrentHourProvider.tick;
57      if(System.currentTimeMillis() < tick.expirationTimeInMillis) {
58        return tick.currentHour;
59      }
60  
61      CurrentHourProvider.tick = tick = nextTick();
62      return tick.currentHour;
63    }
64  }