TimeUnit源码走读及基本使用

Posted amcomputer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TimeUnit源码走读及基本使用相关的知识,希望对你有一定的参考价值。

1 背景介绍

笔者遇到一个场景,用户输入的时间和数据库里面时间做对比,由于数据库里面是timestamp类型,(如 2021-08-23 08:28:41),而用户输入一般为小时,分钟,或者毫秒。代码规约规定不能使用java.sql.Time, java.sql.Date, 和java.sql.timestamp, 因为在jdk8中,这3个类有缺陷。

现在假设用户输入是毫秒 (long startTime = System.currentTimeMillis() ),笔者需要把这个毫秒转变为数据库里面是timestamp类型,笔者尝试了很多方法。最后还是不能避免使用java.sql.Timestamp,核心代码如下:

new Timestamp(new Date(System.currentTimeMillis()).getTime()),

即先把用户输入毫秒转为Date类型,在得到Time,最后转为Timestamp。

虽然能完成任务,需求,可是犯规了,笔者该怎么办?

备注:因为源码比较长, 就放到最后部分了。

2 基本使用

非常好用的TimeUnit类!!!!!

类A是pojo请求类:

class A{
Date StartTime;
Date endTime;
//getter or setter ignore
}

先设置时间:毫秒到秒
```java
A.setStartTime(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));

转化为目标查询参数:

   Date startTime = new Date(TimeUnit.SECONDS.toMillis(A.getStartTime()))

startTime就可以传入sql进行查询了。

下面是具体startTime的数值:

上面只是一个基本demo使用,毫秒,纳秒,微秒,小时,分钟,天等基本单位都很容易实现,只需要TimeUnit.XX.toXXs()转化就行了。

TimeUnit.DAYS //天

TimeUnit.HOURS //小时

TimeUnit.MINUTES //分钟

TimeUnit.SECONDS //秒

TimeUnit.MILLISECONDS //毫秒

TimeUnit.MICROSECONDS //微秒

TimeUnit.NANOSECONDS //纳秒

时间颗粒度转换 :

public long toMillis(long d) ;//转化成毫秒

public long toSeconds(long d) ;//转化成秒

public long toMinutes(long d); //转化成分钟

public long toHours(long d) ;//转化成小时

public long toDays(long d); //转化天

同时,TimeUnit还能延时(与thread.sleep()一样),如thread.sleep(1000)是线程暂定1秒,但thread.sleep(80000)是多少呢?

TimeUnit.SECONDS.sleep( 5 );//暂停5秒
TimeUnit.MINUTES.sleep( 1 );//暂停1分钟

TimeUnit是不是可读性很高?
接下来看源码如何实现。

3 源码

!!!!最重要的部分!!!!

// Handy constants for conversion methods
    static final long C0 = 1L;
    static final long C1 = C0 * 1000L;
    static final long C2 = C1 * 1000L;
    static final long C3 = C2 * 1000L;
    static final long C4 = C3 * 60L;
    static final long C5 = C4 * 60L;
    static final long C6 = C5 * 24L;

    static final long MAX = Long.MAX_VALUE;
    /**
     * Scale d by m, checking for overflow.
     * This has a short name to make above code more readable.
     */
    static long x(long d, long m, long over) {
        if (d >  over) return Long.MAX_VALUE;
        if (d < -over) return Long.MIN_VALUE;
        return d * m;
    }
    ```
其他的比较简单
c0,C1,C2,...,C6分别对应前面介绍的纳秒,微秒,。。。到天,即以纳秒为最小单位,C1 = C0 * 1000L;表上了一微秒等于1000纳秒。C6 = C5 * 24L;表示来一天等于24小时。

static final long MAX = Long.MAX_VALUE; 为最大的Long类型数,我们知道long8个字节(32bit)所以最大的MAX为2^31-1,第一位为符号位。

x(d,m,over)方法为计算由d转为目标级别后换算单位,即d=5,由分钟转秒demo:

   ```java
 
TimeUnit.MINUTES.toSeconds(5)
那么此时会具体执行的函数为:
x(5,60,MAX/(60)),然后判断不超过最大范围,
返回了5*60,即得到了300

源代码如下:

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * This file is available under and governed by the GNU General Public
 * License version 2 only, as published by the Free Software Foundation.
 * However, the following notice accompanied the original version of this
 * file:
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;

/**
 * A {@code TimeUnit} represents time durations at a given unit of
 * granularity and provides utility methods to convert across units,
 * and to perform timing and delay operations in these units.  A
 * {@code TimeUnit} does not maintain time information, but only
 * helps organize and use time representations that may be maintained
 * separately across various contexts.  A nanosecond is defined as one
 * thousandth of a microsecond, a microsecond as one thousandth of a
 * millisecond, a millisecond as one thousandth of a second, a minute
 * as sixty seconds, an hour as sixty minutes, and a day as twenty four
 * hours.
 *
 * <p>A {@code TimeUnit} is mainly used to inform time-based methods
 * how a given timing parameter should be interpreted. For example,
 * the following code will timeout in 50 milliseconds if the {@link
 * java.util.concurrent.locks.Lock lock} is not available:
 *
 *  <pre> {@code
 * Lock lock = ...;
 * if (lock.tryLock(50L, TimeUnit.MILLISECONDS)) ...}</pre>
 *
 * while this code will timeout in 50 seconds:
 *  <pre> {@code
 * Lock lock = ...;
 * if (lock.tryLock(50L, TimeUnit.SECONDS)) ...}</pre>
 *
 * Note however, that there is no guarantee that a particular timeout
 * implementation will be able to notice the passage of time at the
 * same granularity as the given {@code TimeUnit}.
 *
 * @since 1.5
 * @author Doug Lea
 */
public enum TimeUnit {
    /**
     * Time unit representing one thousandth of a microsecond
     */
    NANOSECONDS {
        public long toNanos(long d)   { return d; }
        public long toMicros(long d)  { return d/(C1/C0); }
        public long toMillis(long d)  { return d/(C2/C0); }
        public long toSeconds(long d) { return d/(C3/C0); }
        public long toMinutes(long d) { return d/(C4/C0); }
        public long toHours(long d)   { return d/(C5/C0); }
        public long toDays(long d)    { return d/(C6/C0); }
        public long convert(long d, TimeUnit u) { return u.toNanos(d); }
        int excessNanos(long d, long m) { return (int)(d - (m*C2)); }
    },

    /**
     * Time unit representing one thousandth of a millisecond
     */
    MICROSECONDS {
        public long toNanos(long d)   { return x(d, C1/C0, MAX/(C1/C0)); }
        public long toMicros(long d)  { return d; }
        public long toMillis(long d)  { return d/(C2/C1); }
        public long toSeconds(long d) { return d/(C3/C1); }
        public long toMinutes(long d) { return d/(C4/C1); }
        public long toHours(long d)   { return d/(C5/C1); }
        public long toDays(long d)    { return d/(C6/C1); }
        public long convert(long d, TimeUnit u) { return u.toMicros(d); }
        int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); }
    },

    /**
     * Time unit representing one thousandth of a second
     */
    MILLISECONDS {
        public long toNanos(long d)   { return x(d, C2/C0, MAX/(C2/C0)); }
        public long toMicros(long d)  { return x(d, C2/C1, MAX/(C2/C1)); }
        public long toMillis(long d)  { return d; }
        public long toSeconds(long d) { return d/(C3/C2); }
        public long toMinutes(long d) { return d/(C4/C2); }
        public long toHours(long d)   { return d/(C5/C2); }
        public long toDays(long d)    { return d/(C6/C2); }
        public long convert(long d, TimeUnit u) { return u.toMillis(d); }
        int excessNanos(long d, long m) { return 0; }
    },

    /**
     * Time unit representing one second
     */
    SECONDS {
        public long toNanos(long d)   { return x(d, C3/C0, MAX/(C3/C0)); }
        public long toMicros(long d)  { return x(d, C3/C1, MAX/(C3/C1)); }
        public long toMillis(long d)  { return x(d, C3/C2, MAX/(C3/C2)); }
        public long toSeconds(long d) { return d; }
        public long toMinutes(long d) { return d/(C4/C3); }
        public long toHours(long d)   { return d/(C5/C3); }
        public long toDays(long d)    { return d/(C6/C3); }
        public long convert(long d, TimeUnit u) { return u.toSeconds(d); }
        int excessNanos(long d, long m) { return 0; }
    },

    /**
     * Time unit representing sixty seconds
     */
    MINUTES {
        public long toNanos(long d)   { return x(d, C4/C0, MAX/(C4/C0)); }
        public long toMicros(long d)  { return x(d, C4/C1, MAX/(C4/C1)); }
        public long toMillis(long d)  { return x(d, C4/C2, MAX/(C4/C2)); }
        public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); }
        public long toMinutes(long d) { return d; }
        public long toHours(long d)   { return d/(C5/C4); }
        public long toDays(long d)    { return d/(C6/C4); }
        public long convert(long d, TimeUnit u) { return u.toMinutes(d); }
        int excessNanos(long d, long m) { return 0; }
    },

    /**
     * Time unit representing sixty minutes
     */
    HOURS {
        public long toNanos(long d)   { return x(d, C5/C0, MAX/(C5/C0)); }
        public long toMicros(long d)  { return x(d, C5/C1, MAX/(C5/C1)); }
        public long toMillis(long d)  { return x(d, C5/C2, MAX/(C5/C2)); }
        public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); }
        public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); }
        public long toHours(long d)   { return d; }
        public long toDays(long d)    { return d/(C6/C5); }
        public long convert(long d, TimeUnit u) { return u.toHours(d); }
        int excessNanos(long d, long m) { return 0; }
    },

    /**
     * Time unit representing twenty four hours
     */
    DAYS {
        public long toNanos(long d)   { return x(d, C6/C0, MAX/(C6/C0)); }
        public long toMicros(long d)  { return x(d, C6/C1, MAX/(C6/C1)); }
        public long toMillis(long d)  { return x(d, C6/C2, MAX/(C6/C2)); }
        public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); }
        public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); }
        public long toHours(long d)   { return x(d, C6/C5, MAX/(C6/C5)); }
        public long toDays(long d)    { return d; }
        public long convert(long d, TimeUnit u) { return u.toDays(d); }
        int excessNanos(long d, long m) { return 0; }
    };

    // Handy constants for conversion methods
    static final long C0 = 1L;
    static final long C1 = C0 * 1000L;
    static final long C2 = C1 * 1000L;
    static final long C3 = C2 * 1000L;
    static final long C4 = C3 * 60L;
    static final long C5 = C4 * 60L;
    static final long C6 = C5 * 24L;

    static final long MAX = Long.MAX_VALUE;

    /**
     * Scale d

以上是关于TimeUnit源码走读及基本使用的主要内容,如果未能解决你的问题,请参考以下文章

JAVA源码走读 HashMap与ArrayList

kcp源码走读

[redis 源码走读] sentinel 哨兵 - 节点发现流程

JAVA进阶之路-AbstractQueuedSynchronizer(AQS)源码走读

JAVA进阶之路-AbstractQueuedSynchronizer(AQS)源码走读

20170908工作日记--UML画类图HTTP协议Volley源码走读