| 1 | package org.jtoolkit.essence.utils; |
| 2 | |
| 3 | import org.jetbrains.annotations.NotNull; |
| 4 | import org.jetbrains.annotations.Nullable; |
| 5 | import org.jtoolkit.essence.concurrency.ThreadSafe; |
| 6 | |
| 7 | import java.io.Closeable; |
| 8 | import java.util.concurrent.atomic.AtomicBoolean; |
| 9 | |
| 10 | /* |
| 11 | Copyright 2006 Peter Lawrey |
| 12 | |
| 13 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 14 | you may not use this file except in compliance with the License. |
| 15 | You may obtain a copy of the License at |
| 16 | |
| 17 | http://www.apache.org/licenses/LICENSE-2.0 |
| 18 | |
| 19 | Unless required by applicable law or agreed to in writing, software |
| 20 | distributed under the License is distributed on an "AS IS" BASIS, |
| 21 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 22 | See the License for the specific language governing permissions and |
| 23 | limitations under the License. |
| 24 | */ |
| 25 | |
| 26 | /** |
| 27 | * A factory interface which creates object based on a description. These object can be returned to the factory for recycling and disposal. |
| 28 | * |
| 29 | * @author Peter Lawrey |
| 30 | */ |
| 31 | @ThreadSafe |
| 32 | public interface Factory<D, E> extends Closeable, Named { |
| 33 | /** |
| 34 | * Create or recycle an object suitable for the description. |
| 35 | */ |
| 36 | @NotNull public E acquire(D description) throws InterruptedException; |
| 37 | |
| 38 | /** |
| 39 | * Release, recycle or dispose of an object this factory created. |
| 40 | */ |
| 41 | public void release(@Nullable E element); |
| 42 | |
| 43 | /** |
| 44 | * Base class for factory implementations. |
| 45 | */ |
| 46 | public abstract class AbstractFactory<D, E> implements Factory<D, E> { |
| 47 | protected final String name; |
| 48 | protected final AtomicBoolean closed = new AtomicBoolean(false); |
| 49 | |
| 50 | protected AbstractFactory(String name) { |
| 51 | this.name = name; |
| 52 | } |
| 53 | |
| 54 | @NotNull public String getName() { |
| 55 | return name; |
| 56 | } |
| 57 | |
| 58 | public void close() { |
| 59 | closed.set(true); |
| 60 | } |
| 61 | |
| 62 | public void release(E element) { |
| 63 | if (element == null) return; |
| 64 | if (element instanceof Closeable) |
| 65 | IOUtils.close((Closeable) element); |
| 66 | } |
| 67 | |
| 68 | @Override protected void finalize() throws Throwable { |
| 69 | super.finalize(); |
| 70 | if (!closed.get()) close(); |
| 71 | } |
| 72 | } |
| 73 | } |