All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zuunr.json.JsonValueSupportedPojoCache Maven / Gradle / Ivy

There is a newer version: 0.1.4
Show newest version
/*
 * Copyright 2020 Zuunr AB
 *
 * 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
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.zuunr.json;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Niklas Eldberger
 */
class JsonValueSupportedPojoCache {

    private Entry entry1;
    private Entry entry2;
    private ConcurrentHashMap map;

    public JsonValueSupportedPojoCache() {
    }

    public JsonValueSupportedPojoCache putPojo(Class clazz, Object pojo) {

        if (entry1 == null) {
            entry1 = new Entry(clazz, pojo);
        } else if (entry2 == null) {
            entry2 = new Entry(clazz, pojo);
        } else {
            if (map == null) {
                map = new ConcurrentHashMap<>();
            }
            map.put(clazz, pojo);
        }
        return this;
    }


    public Object getPojo(Class clazz) {
        Entry entry = getEntry(clazz);

        if (entry != null) {
            return entry.getPojo();
        } else {
            if (map == null) {
                return null;
            } else {
                return map.get(clazz);
            }
        }
    }

    private Entry getEntry(Class clazz) {

        // Make sure values do not change from other thread while evaluating in this method
        Entry entry1 = this.entry1;
        Entry entry2 = this.entry2;

        if (entry1 == null) {
            return null;
        } else if (entry1.getKey() == clazz) {
            return entry1;
        } else if (entry2 == null) {
            return null;
        } else if (entry2.getKey() == clazz) {
            return entry2;
        } else {
            return null;
        }

    }

    static class Entry  {
        private final Class key;
        private final Object pojo;

        public Entry(java.lang.Class key, java.lang.Object pojo) {
            this.key = key;
            this.pojo = pojo;
        }

        public Class getKey() {
            return key;
        }

        public Object getPojo() {
            return pojo;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy