Distributed systems

Idempotent operation key

Replay the stored result; reject conflicting reuse. Executed Java 21 model, not framework integration.

Formal Syntax & Structure

java syntaxjava
synchronized reserve(key,n)

Working Example

Example Snippetjava
public class Main {    record Result(int quantity, int remaining) {}    static class Store {        int stock=5;        final java.util.Map<String,Result> done=new java.util.HashMap<>();        synchronized Result reserve(String key,int n) {            if(n<=0) throw new IllegalArgumentException("quantity");            var old=done.get(key);            if(old!=null) { if(old.quantity()!=n) throw new IllegalArgumentException("key conflict"); return old; }            if(n>stock) throw new IllegalStateException("insufficient stock");            stock-=n; var result=new Result(n,stock); done.put(key,result); return result;        }    }    public static void main(String[] args) {        var s = new Store();        System.out.println(s.reserve("tenant:A:K1", 2));        System.out.println(s.reserve("tenant:A:K1", 2));        System.out.println(s.stock);    }}
Java Reference