001/*
002 * jPOS Project [http://jpos.org]
003 * Copyright (C) 2000-2026 jPOS Software SRL
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jpos.util;
020
021import java.util.concurrent.TimeUnit;
022import java.util.function.Supplier;
023
024public class StopWatch {
025    long end;
026    public StopWatch (long period, TimeUnit unit) {
027        end = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(period, unit);
028    }
029    public StopWatch (long periodInMillis) {
030        this (periodInMillis, TimeUnit.MILLISECONDS);
031    }
032    public void finish() {
033        long now = System.currentTimeMillis();
034        if (end > now) {
035            try {
036                Thread.sleep(end - now);
037            } catch (InterruptedException ignored) { }
038        }
039    }
040    public boolean isFinished() {
041        return System.currentTimeMillis() >= end;
042    }
043
044    public static <T> T get(long period, TimeUnit unit, Supplier<T> f) {
045        StopWatch w = new StopWatch(period, unit);
046        T t = f.get();
047        w.finish();
048        return t;
049    }
050
051    public static <T> T get(long period, Supplier<T> f) {
052        return get(period, TimeUnit.MILLISECONDS, f);
053    }
054}