001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.utils; 014 015import java.util.concurrent.atomic.*; 016 017/** 018 * Predefined ID generators. 019 */ 020public class IdGenerators { 021 022 /** 023 * Creates an ID generator using {@link AtomicInteger} initialized to value <code>1</code>. 024 * 025 * @param initValue The initial value. 026 * @return A new ID generator. 027 */ 028 public static IdGenerator<Integer> createIntGenerator(final int initValue) { 029 return new IdGenerator<Integer>() { 030 private final AtomicInteger i = new AtomicInteger(initValue); 031 032 @Override /* IdGenerator */ 033 public synchronized Integer next() { 034 return i.getAndIncrement(); 035 } 036 037 @Override 038 public synchronized void lb(Integer k) { 039 i.set(Math.max(k + 1, i.get())); 040 } 041 }; 042 } 043 044 /** 045 * Creates an ID generator using {@link AtomicInteger} initialized to the specified value. 046 * 047 * @return A new ID generator. 048 */ 049 public static IdGenerator<Integer> createIntGenerator() { 050 return createIntGenerator(1); 051 } 052 053 /** 054 * Creates an ID generator using {@link AtomicLong} initialized to value <code>1</code>. 055 * 056 * @param initValue The initial value. 057 * @return A new ID generator. 058 */ 059 public static IdGenerator<Long> createLongGenerator(final long initValue) { 060 return new IdGenerator<Long>() { 061 private final AtomicLong l = new AtomicLong(initValue); 062 063 @Override /* IdGenerator */ 064 public synchronized Long next() { 065 return l.getAndIncrement(); 066 } 067 068 @Override 069 public synchronized void lb(Long k) { 070 l.set(Math.max(k + 1, l.get())); 071 } 072 }; 073 } 074 075 /** 076 * Creates an ID generator using {@link AtomicLong} initialized to the specified value. 077 * 078 * @return A new ID generator. 079 */ 080 public static IdGenerator<Long> createLongGenerator() { 081 return createLongGenerator(1); 082 } 083}