LongBitFormat是一个工具类,可以把多项小的数据值压缩在一个long类型的数据中,以下为一个测试用例,PREFERED_BLOCK_SIZE占48位,REPLICATION占12位,STORAGE_POLICY_ID占4位,共占64位,并且提供了从一个long类型值中,提取各值的方法。还提供了一个根据各值,得到组合的long值的方法toLong(long preferredBlockSize, short replication,
byte storagePolicyID)。
import org.apache.hadoop.hdfs.server.blockmanagement.BlockStoragePolicySuite;
import org.apache.hadoop.hdfs.util.LongBitFormat;
public class LongFormatTest {
static enum HeaderFormat {
PREFERRED_BLOCK_SIZE(null, 48, 1),
REPLICATION(PREFERRED_BLOCK_SIZE.BITS, 12, 1),
STORAGE_POLICY_ID(REPLICATION.BITS, BlockStoragePolicySuite.ID_BIT_LENGTH,
0);
private final LongBitFormat BITS;
private HeaderFormat(LongBitFormat previous, int length, long min) {
BITS = new LongBitFormat(name(), previous, length, min);
}
static short getReplication(long header) {
return (short)REPLICATION.BITS.retrieve(header);
}
static long getPreferredBlockSize(long header) {
return PREFERRED_BLOCK_SIZE.BITS.retrieve(header);
}
static byte getStoragePolicyID(long header) {
return (byte)STORAGE_POLICY_ID.BITS.retrieve(header);
}
static long toLong(long preferredBlockSize, short replication,
byte storagePolicyID) {
long h = 0;
h = PREFERRED_BLOCK_SIZE.BITS.combine(preferredBlockSize, h);
h = REPLICATION.BITS.combine(replication, h);
h = STORAGE_POLICY_ID.BITS.combine(storagePolicyID, h);
return h;
}
}
public static void main(String[] args) {
long blockSize = 512;
System.out.println("block size: " + HeaderFormat.getPreferredBlockSize(blockSize));
long replication = 3L << 48;
System.out.println("replication: " + HeaderFormat.getReplication(replication));
long storagePolicyID = 2L << 60;
System.out.println("storagePolicyID: " + HeaderFormat.getStoragePolicyID(storagePolicyID));
System.out.println("added value: "+ (blockSize + replication +storagePolicyID));
System.out.println("get combined value :" + HeaderFormat.toLong(512, (short)3 , (byte)2));
}
}