class RefCountedItem<T> implements AutoCloseable {

    private final Function<String, T> itemFactory;
    private final Consumer<T> closeItem;
    private final ArrayList<String> sources = new ArrayList<>();

    private int refs = 0;
    private T item;

    public RefCountedItem(Function<String, T> itemFactory, Consumer<T> closeItem) {
        this.itemFactory = itemFactory;
        this.closeItem = closeItem;
    }

    /**
     * Marks resource as acquired by `source`.
     * On the first acquisition the item is created.
     *
     * <p>
     * If {@link #itemFactory} raises an error the ref-counter is <b>not</b> incremented.
     * </p>
     */
    public void markAcquired(String source) {
        synchronized (sources) {
            if (item == null) {
                item = itemFactory.apply(source);
            }
            sources.add(source);
            refs++;
        }
    }

    public T item() {
        synchronized (sources) {
            if (item == null) {
                assert !sources.isEmpty() : "Must call `markAcquired` to be able to access the item";
                item = itemFactory.apply(sources.get(sources.size() - 1));
            }
            return item;
        }
    }

    @Override
    public void close() {<FILL_FUNCTION_BODY>}
}

        synchronized (sources) {
            refs--;
            if (refs == 0) {
                try {
                    closeItem.accept(item);
                } finally {
                    item = null;
                }
            }
        }
    
<no_super_class>