Java tutorial
/** * Copyright 2013 Ben Navetta <ben@bennavetta.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bennavetta.appsite.processor.scripting; import java.util.concurrent.TimeUnit; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; public class ScriptFactory { private ScriptCompiler compiler; private LoadingCache<String, Script> cache; public ScriptFactory(ScriptCompiler compiler, long maxSize, long scriptLife, TimeUnit unit) { this.compiler = compiler; this.cache = CacheBuilder.newBuilder().maximumSize(maxSize).expireAfterWrite(scriptLife, unit) .build(new CacheLoader<String, Script>() { @Override public Script load(String key) throws Exception { return ScriptFactory.this.compiler.compile(key); } }); } public ScriptFactory(ScriptCompiler compiler) { this(compiler, 100, 10, TimeUnit.MINUTES); // don't use a really big value for the expiration because we don't want to keep old/rarely used scripts around forever } public Script getScript(String source) throws Exception { return cache.get(source); } public ScriptCompiler getCompiler() { return compiler; } public void setCompiler(ScriptCompiler compiler) { this.compiler = compiler; } }