Write a function that guarantees to never return the same value twice
Write a function that guarantees to never return the same value twice
To write a function that guarantees to never return the same value twice, especially in a concurrent environment, you need to ensure that the function is thread-safe and can handle multiple threads accessing it simultaneously. Here is a Java implementation using AtomicLong
to achieve this:
import java.util.concurrent.atomic.AtomicLong;
public class UniqueValueGenerator {
private final AtomicLong counter = new AtomicLong();
public long getNextUniqueValue() {
return counter.getAndIncrement();
}
public static void main(String[] args) {
UniqueValueGenerator generator = new UniqueValueGenerator();
// Example usage
System.out.println(generator.getNextUniqueValue()); // 0
System.out.println(generator.getNextUniqueValue()); // 1
System.out.println(generator.getNextUniqueValue()); // 2
}
}
AtomicLong: This class provides a thread-safe way to handle long values. The getAndIncrement()
method atomically increments the current value and returns the previous value, ensuring that each call to getNextUniqueValue()
returns a unique value.
Thread Safety: By using AtomicLong
, we avoid the need for explicit synchronization, which can be error-prone and less performant. The atomic operations provided by AtomicLong
ensure that even in a highly concurrent environment, each thread will receive a unique value.
In the main
method, we demonstrate how to use the UniqueValueGenerator
class. Each call to getNextUniqueValue()
returns a unique value, starting from 0 and incrementing by 1 with each call.
This approach ensures that the function is both thread-safe and efficient, making it suitable for use in a multi-threaded application where unique values are requi...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào