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

org.mentalog.util.StringBuilderPool Maven / Gradle / Ivy

There is a newer version: 2.1.2
Show newest version
package org.mentalog.util;

import java.util.ArrayList;
import java.util.List;

/**
 * This code is NOT thread-safe at all.
 * 
 * You can use to_sb to bypass autoboxing and avoid the object creation. So intead of:
 * 
 * Info.log(myInteger);
 * 
 * you would do:
 * 
 * Info.log(to_sb(myInteger));
 * 
 * NOTE: If you want to use this from multiple threads you MUST synchronize around to_sb:
 * 
 * synchronized(Info) { Info.log(to_sb(myInteger)); }
 * 
 * @author Sergio Oliveira Jr.
 */
class StringBuilderPool {

	private static final int SB_SIZE = 32;
	private static final int POOL_SIZE = 16;

	private final List sbs = new ArrayList(POOL_SIZE);
	private int pointer = 0;

	public StringBuilderPool() {
		for (int i = 0; i < POOL_SIZE; i++) {
			sbs.add(new StringBuilder(SB_SIZE));
		}
	}

	public StringBuilder get() {
		if (pointer >= sbs.size()) {
			return new StringBuilder(SB_SIZE);
		}
		StringBuilder sb = sbs.get(pointer++);
		sb.setLength(0);
		return sb;
	}

	public final void reset() {
		pointer = 0;
	}

	public final int getPointer() {
		return pointer;
	}

	public final StringBuilder to_sb(int x) {
		return to_sb((long) x);
	}

	public final StringBuilder to_sb(long x) {
		StringBuilder sb = get();
		StringUtils.append(sb, x);
		return sb;
	}

	public final StringBuilder to_sb(byte b) {
		return to_sb((long) b);
	}

	public final StringBuilder to_sb(short s) {
		return to_sb((long) s);
	}

	public final StringBuilder to_sb(double x) {
		StringBuilder sb = get();
		StringUtils.append(sb, x);
		return sb;
	}

	public final StringBuilder to_sb(boolean b) {
		StringBuilder sb = get();
		if (b) {
			sb.append("true");
		} else {
			sb.append("false");
		}
		return sb;
	}

	public final StringBuilder to_sb(float f) {
		return to_sb((double) f);
	}

	public final StringBuilder to_sb(char c) {
		StringBuilder sb = get();
		sb.append(c);
		return sb;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy