001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017: package org.apache.wicket.threadtest.apps.app2;
018:
019: import java.util.Stack;
020:
021: import org.apache.commons.logging.Log;
022: import org.apache.commons.logging.LogFactory;
023:
024: /**
025: * Test pool.
026: *
027: * @author eelcohillenius
028: */
029: public class Pool {
030:
031: private static Pool _instance = new Pool();
032:
033: private static Log log = LogFactory.getLog(Pool.class);
034:
035: public static Connection getConnection() {
036: return getInstance().doGetConnection();
037: }
038:
039: public static Pool getInstance() {
040: return _instance;
041: }
042:
043: public static void release() {
044: getInstance().doRelease();
045: }
046:
047: private Connection[] allConnections;
048:
049: private Stack<Connection> available = new Stack<Connection>();
050:
051: private ThreadLocal<Connection> locks = new ThreadLocal<Connection>();
052:
053: private int size = 3;
054:
055: private Pool() {
056:
057: allConnections = new Connection[size];
058: for (int i = 0; i < size; i++) {
059: Connection connection = new Connection(String.valueOf(i));
060: allConnections[i] = connection;
061: available.push(connection);
062: }
063: }
064:
065: private synchronized Connection doGetConnection() {
066:
067: Connection c = locks.get();
068:
069: if (c != null) {
070: return c;
071:
072: } else {
073:
074: while (c == null) {
075:
076: if (!available.isEmpty()) {
077: c = available.pop();
078: locks.set(c);
079: log.info("returning " + c + " for "
080: + Thread.currentThread());
081: } else {
082: try {
083: log.info("enter wait for "
084: + Thread.currentThread());
085: wait();
086: } catch (InterruptedException e) {
087: throw new RuntimeException(e);
088: }
089: }
090: }
091: }
092: return c;
093: }
094:
095: private synchronized void doRelease() {
096: Connection c = locks.get();
097: if (c != null) {
098: available.push(c);
099: locks.remove();
100: log.info("releasing " + c + " for "
101: + Thread.currentThread());
102: notifyAll();
103: }
104: }
105: }
|