001/* 002 * SonarQube 003 * Copyright (C) 2009-2018 SonarSource SA 004 * mailto:info AT sonarsource DOT com 005 * 006 * This program is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * This program is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020package org.sonar.api.utils.internal; 021 022import java.util.Random; 023import java.util.concurrent.atomic.AtomicLong; 024import java.util.function.Supplier; 025import org.sonar.api.utils.System2; 026 027import static com.google.common.base.Preconditions.checkArgument; 028 029/** 030 * A subclass of {@link System2} which implementation of {@link System2#now()} always return a bigger value than the 031 * previous returned value. 032 * <p> 033 * This class is intended to be used in Unit tests. 034 * </p> 035 */ 036public class AlwaysIncreasingSystem2 extends System2 { 037 private final AtomicLong now; 038 private final long increment; 039 040 private AlwaysIncreasingSystem2(Supplier<Long> initialValueSupplier, long increment) { 041 checkArgument(increment > 0, "increment must be > 0"); 042 long initialValue = initialValueSupplier.get(); 043 checkArgument(initialValue >= 0, "Initial value must be >= 0"); 044 this.now = new AtomicLong(initialValue); 045 this.increment = increment; 046 } 047 048 public AlwaysIncreasingSystem2(long increment) { 049 this(AlwaysIncreasingSystem2::randomInitialValue, increment); 050 } 051 052 public AlwaysIncreasingSystem2(long initialValue, int increment) { 053 this(() -> initialValue, increment); 054 } 055 056 /** 057 * Values returned by {@link #now()} will start with a random value and increment by 100. 058 */ 059 public AlwaysIncreasingSystem2() { 060 this(AlwaysIncreasingSystem2::randomInitialValue, 100); 061 } 062 063 @Override 064 public long now() { 065 return now.getAndAdd(increment); 066 } 067 068 private static long randomInitialValue() { 069 return (long) Math.abs(new Random().nextInt(2_000_000)); 070 } 071}