//============================================================================= // Copyright 2006-2010 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //============================================================================= package org.uncommons.util.id; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * <p>Thread-safe source for partitioned unique IDs. A single instance of this class * represents a single 'partition' in the space of possible IDs. By creating * multiple instances with different discriminators, multiple entities may generate * globally unique IDs independently.</p> * <p>Any given instance of this class may generate a maximum of 2^31 unique values * (the most significant 4 bytes are fixed and the least significant 4 bytes vary * in sequence).</p> * @author Daniel Dyer */ public final class CompositeIDSource implements IDSource<Long> { private final Lock lock = new ReentrantLock(); private final long top32bits; private final IDSource<Integer> sequence = new IntSequenceIDSource(); /** * @param topPart The most significant 32 bits to use for the 64-bit IDs generated * by this source. All IDs generated by this source will have the same top 4 bytes. */ public CompositeIDSource(int topPart) { top32bits = ((long) topPart) << 32; } /** * {@inheritDoc} */ public Long nextID() { lock.lock(); try { // Top part is value provided in constructor, lower 32 bits are from the sequence. return (top32bits + sequence.nextID()); } finally { lock.unlock(); } } }