001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.io;
019
020import java.nio.ByteBuffer;
021import org.apache.hadoop.hbase.util.Bytes;
022import org.apache.yetus.audience.InterfaceAudience;
023import org.slf4j.Logger;
024import org.slf4j.LoggerFactory;
025
026/**
027 * A ByteBuffAllocator that rewrite the bytebuffers right after released. It can be used for test
028 * whether there are prematurely releasing backing bytebuffers.
029 */
030@InterfaceAudience.Private
031public class DeallocateRewriteByteBuffAllocator extends ByteBuffAllocator {
032  private static final Logger LOG =
033    LoggerFactory.getLogger(DeallocateRewriteByteBuffAllocator.class);
034
035  DeallocateRewriteByteBuffAllocator(boolean reservoirEnabled, int maxBufCount, int bufSize,
036    int minSizeForReservoirUse) {
037    super(reservoirEnabled, maxBufCount, bufSize, minSizeForReservoirUse);
038  }
039
040  @Override
041  protected void putbackBuffer(ByteBuffer buf) {
042    if (buf.capacity() != bufSize || (reservoirEnabled ^ buf.isDirect())) {
043      LOG.warn("Trying to put a buffer, not created by this pool! Will be just ignored");
044      return;
045    }
046    buf.clear();
047    byte[] tmp = generateTmpBytes(buf.capacity());
048    buf.put(tmp, 0, tmp.length);
049    super.putbackBuffer(buf);
050  }
051
052  private byte[] generateTmpBytes(int length) {
053    StringBuilder result = new StringBuilder();
054    while (result.length() < length) {
055      result.append("-");
056    }
057    return Bytes.toBytes(result.substring(0, length));
058  }
059}