/*******************************************************************************
 * Copyright (c) 2024-2025 R3944Realms. All rights reserved.
 * <p>
 * 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
 * <p>
 *     http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 com.r3944realms.dg_lab.utils.unSafe;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;

/**
 * The type Atomic class.
 *
 * @param <T> the type parameter
 */
@SuppressWarnings("FieldMayBeFinal")
public class AtomicClass<T> {
    private static final VarHandle VALUE;
    private volatile T value;

    /**
     * Instantiates a new Atomic class.
     *
     * @param value the value
     */
    public AtomicClass(T value) {
        this.value = value;
    }
    static {
        try {
            Field valueField = AtomicClass.class.getDeclaredField("value");
            VALUE = MethodHandles.lookup().unreflectVarHandle(valueField);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Get t.
     *
     * @return the t
     */
    public T get() {
        return value;
    }

    /**
     * Set.
     *
     * @param newValue the new value
     */
    public void set(T newValue) {
        while (true) {
            //noinspection unchecked
            T prev = (T) VALUE.getVolatile(this);
            if (VALUE.compareAndSet(this, prev, newValue)) {
                break;
            }
        }
    }
}
