• java BufferSegment


    package org.rx.util;
    
    import java.util.function.Consumer;
    
    import static org.rx.core.Contract.require;
    
    public class BufferSegment {
        private final byte[] buffer;
        private final int bufferSize;
        private volatile int offset;
        private volatile boolean autoReleased;
    
        public boolean isAutoReleased() {
            return autoReleased;
        }
    
        public void setAutoReleased(boolean autoReleased) {
            this.autoReleased = autoReleased;
        }
    
        public BufferSegment(int bufferSize, int bufferCount) {
            require(bufferSize, bufferSize >= 0);
            require(bufferCount, bufferCount >= 0);
    
            buffer = new byte[(this.bufferSize = bufferSize) * bufferCount];
        }
    
        public BytesSegment alloc() {
            if (offset == buffer.length) {
                return new BytesSegment(new byte[bufferSize]);
            }
    
            synchronized (buffer) {
                BytesSegment segment = new BytesSegment(buffer, offset, bufferSize);
                offset += bufferSize;
                if (autoReleased) {
                    segment.Closed = p -> release(p);
                }
                return segment;
            }
        }
    
        public void release(BytesSegment segment) {
            require(segment);
    
            if (buffer != segment.array) {
                return;
            }
    
            synchronized (buffer) {
                offset -= segment.count;
            }
        }
    
        public void accept(Consumer<BytesSegment> consumer) {
            require(consumer);
    
            try (BytesSegment segment = alloc()) {
                consumer.accept(segment);
            }
        }
    }
  • 相关阅读:
    单例模式的三种写法
    ASP.NET如何下载大文件
    字符串是引用类型
    SQL 事务隔离级别
    Sql Server 锁
    设非主键为聚集索引
    C#如何使用SqlCacheDependency
    简易系统后台架构
    matlab cross 3*1 向量叉乘
    Matlab求齐次方程的解
  • 原文地址:https://www.cnblogs.com/Googler/p/11725024.html
Copyright © 2020-2023  润新知