1/* 2 * Copyright (C) 2010 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.google.clearsilver.jsilver.output; 18 19/** 20 * Implementation of OutputBufferProvider that reuses the same StringBuilder in each Thread. 21 */ 22public class ThreadLocalOutputBufferProvider implements OutputBufferProvider { 23 24 private final ThreadLocal<StringBuilder> pool; 25 private final ThreadLocal<Boolean> available; 26 27 public ThreadLocalOutputBufferProvider(final int bufferSize) { 28 pool = new ThreadLocal<StringBuilder>() { 29 protected StringBuilder initialValue() { 30 return new StringBuilder(bufferSize); 31 } 32 }; 33 available = new ThreadLocal<Boolean>() { 34 protected Boolean initialValue() { 35 return true; 36 } 37 }; 38 } 39 40 @Override 41 public Appendable get() { 42 if (!available.get()) { 43 throw new IllegalStateException("Thread buffer is not free."); 44 } 45 StringBuilder sb = pool.get(); 46 available.set(false); 47 sb.setLength(0); 48 return sb; 49 } 50 51 @Override 52 public void release(Appendable buffer) { 53 if (buffer != pool.get()) { 54 throw new IllegalArgumentException("Can't release buffer that does not " 55 + "correspond to this thread."); 56 } 57 available.set(true); 58 } 59} 60