Câu hỏi phỏng vấn Concurrency
Câu hỏi

Write a function that guarantees to never return the same value twice

Câu trả lời

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
    }
}

Explanation

  1. 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.

  2. 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.

Usage

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

middle

Gợi ý câu hỏi phỏng vấn

middle

Explain Deadlock to 5 years old

middle

What is the meaning of the term “Thread-Safe”?

junior

What is a Mutex?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào