001/*
002 * Copyright 2014 Alex Kasko (alexkasko.com)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.alexkasko.unsafe.offheap;
018
019import java.util.NoSuchElementException;
020
021/**
022 * Static utility methods for off-heap classes
023 *
024 * @author alexkasko
025 * Date: 3/5/13
026 */
027public class OffHeapUtils {
028    /**
029     * Utility method for usage in {@code finally} clauses.
030     * Calls {@link com.alexkasko.unsafe.offheap.OffHeapDisposable#free()}
031     * on provided instance only if instance is not null.
032     *
033     * @param disposable off-heap disposable instance, may be null
034     */
035    public static void free(OffHeapDisposable disposable) {
036        if(null == disposable) return;
037        disposable.free();
038    }
039
040    /**
041     * Utility method for usage in {@code finally} clauses.
042     * Calls {@link com.alexkasko.unsafe.offheap.OffHeapDisposable#free()}
043     * on all provided instances only if instance is not null.
044     *
045     * @param disposables one or more off-heap disposable
046     */
047    public static void freeAll(OffHeapDisposable... disposables) {
048        for(OffHeapDisposable di : disposables) {
049            free(di);
050        }
051    }
052
053    /**
054     * Returns empty disposable iterator
055     *
056     * @param <T> generic param
057     * @return empty disposable iterator
058     */
059    public static <T> OffHeapDisposableIterator<T> emptyDisposableIterator() {
060        return new EmptyDisposableIterator<T>();
061    }
062
063    /**
064     * Returns empty instance of {@link com.alexkasko.unsafe.offheap.OffHeapDisposableIterator}
065     *
066     * @param <T>
067     */
068    private static class EmptyDisposableIterator<T> implements OffHeapDisposableIterator<T> {
069
070        @Override
071        public boolean hasNext() {
072            return false;
073        }
074
075        @Override
076        public T next() {
077            throw new NoSuchElementException();
078        }
079
080        @Override
081        public void remove() {
082            throw new UnsupportedOperationException("remove");
083        }
084
085        @Override
086        public void free() {
087            // NOOP
088        }
089
090        @Override
091        public long size() {
092            return 0;
093        }
094    }
095}