たぷつきません

おなかがでてきた。もうたぷついてるやん。

日付のフォーマット

 commons.langのFastDateFormat、java6からの和暦対応してほしいなぁ。いつになったらプール作成から解放されるんだろう。commons.poolは使わないクラスがてんこ盛りだしジェネリックス使えないしで、Poolクラスを作成。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Pool<T> {

    private static int DEFAULT_POOL_MAX = 10;
    
    public static <T> Pool<T> create(T... stocks) {
        return new Pool<T>(Arrays.asList(stocks));
    }
    
    public static <T extends Cloneable> Pool<T> create(T origin) {
        return create(origin, DEFAULT_POOL_MAX);
    }
    
    public static <T extends Cloneable> Pool<T> create(T origin, int poolMax) {
        if (origin == null) {
            throw new IllegalArgumentException("origin: " + origin);
        }
        if (poolMax < 1) {
            throw new IllegalArgumentException("poolMax: " + poolMax);
        }
        List<T> copies = new ArrayList<T>();
        for (int i = 0; i < poolMax; i++) {
            try {
                @SuppressWarnings("unchecked")
                T copied = (T)origin.getClass().getMethod("clone").invoke(origin);
                copies.add(copied);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
        return new Pool<T>(copies);
    }
    
    private Pool(List<T> stocks) {
        if (stocks == null || stocks.size() == 0) {
            throw new IllegalArgumentException("stocks: " + stocks);
        }
        stock = new ArrayList<T>();
        havings = new HashSet<T>();
        for (T stockItem: stocks) {
            stock.add(stockItem);
            havings.add(stockItem);
        }
    }
    
    private List<T> stock;
    private Set<T> havings;
    
    public T borrow() {
        try {
            while (true) {
                synchronized(stock) {
                    if (stock.size() > 0) {
                        return stock.remove(0);
                    }
                }
                Thread.sleep(10);
            }
        } catch(InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
    
    public void giveBack(T item) {
        if (!havings.contains(item)) {
            throw new IllegalStateException("item is not mine");
        }
        synchronized(stock) {
            stock.add(item);
        }
    }
}

 使うときはこんな感じ。

private static Pool<SimpleDateFormat> dateFormatPool =
        Pool.create(
                new SimpleDateFormat(
                        "GGGGyy'年'M'月'd'日'",
                        new Locale("ja","JP","JP")));
:
    public String getPrintDate() {
        SimpleDateFormat formatter = dateFormatPool.borrow();
        try {
            return formatter.format(getDate());
        } finally {
            dateFormatPool.giveBack(formatter);
        }
    }
: