search
HomeJavajavaTutorialJava design pattern implementation object pool pattern example

ObjectPool abstract parent class

import java.util.Iterator;
import java.util.Vector;
public abstract class ObjectPool<T> {

   private Vector<T> locked, unlocked;   // locked是已占用的对象集合,unlocked是可用对象集合

   public ObjectPool() {
    locked = new Vector<T>();
    unlocked = new Vector<T>();
   }
   // 创建对象
   protected abstract T create();
   // 验证对象有效性
   public abstract boolean validate(T o);
   // 使对象失效
   public abstract void expire(T o);
   // 检出:从对象池获取对象
   public synchronized T checkOut() {
    T t;
    if (unlocked.size() > 0) {
     Iterator<T> iter = unlocked.iterator();
     while(iter.hasNext()) {
      t = iter.next();
      if(validate(t)) {   // 对象有效
       unlocked.remove(t);
       locked.add(t);

       return t;
      }
      else {   // 对象已经失效
       unlocked.remove(t);
       expire(t);
      }
     }
    }

    // 对象池塘没有可用对象,创建新对象
    t = create();
    locked.add(t);

    return (t);
   }
   // 检入:释放对象回对象池
   public synchronized void checkIn(T t) {
    locked.remove(t);
    if(validate(t)) {   // 如果对象仍有效则放回可用对象集合中
     unlocked.add(t);
    }
    else {   // 否则使对象失效
     expire(t);
    }
   }

}

JDBCConnectionPool subclass

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCConnectionPool extends ObjectPool<Connection> {

 private String url, usr, pwd;
 public JDBCConnectionPool(String driver, String url, String usr, String pwd) {
  super();

  // 加载对应的数据库驱动
  try {
   Class.forName(driver).newInstance();
  }
  catch(Exception e) {
   e.printStackTrace();
  }

  this.url = url;
  this.usr = usr;
  this.pwd = pwd;
 }

 @Override
 protected Connection create() {
  try {
   return DriverManager.getConnection(url, usr, pwd);
  }
  catch(SQLException e) {
   e.printStackTrace();
  }

  return null;
 }
 @Override
 public boolean validate(Connection o) {
  try {
   return o.isClosed();
  }
  catch(SQLException e) {
   e.printStackTrace();
  }

  return false;
 }
 @Override
 public void expire(Connection o) {
  try {
   o.close();
  }
  catch(SQLException e) {
   e.printStackTrace();
  }
  finally {
   o = null;
  }
 }

 public static void main(String[] args) {
  JDBCConnectionPool dbConnPool = new JDBCConnectionPool("com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/test", "root", "123");

  // 获取数据库连接对象
  Connection conn = dbConnPool.checkOut();

  // 使用数据库连接对象
  // ...

  // 释放数据库连接对象
  dbConnPool.checkIn(conn);

 }
}
class Pool {
   private static final MAX_AVAILABLE = 100;
   private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
   public Object getItem() throws InterruptedException {
     available.acquire();
     return getNextAvailableItem();
   }
   public void putItem(Object x) {
     if (markAsUnused(x))
       available.release();
   }
   // Not a particularly efficient data structure; just for demo
   protected Object[] items = ... whatever kinds of items being managed
   protected boolean[] used = new boolean[MAX_AVAILABLE];
   protected synchronized Object getNextAvailableItem() {
     for (int i = 0; i < MAX_AVAILABLE; ++i) {
       if (!used[i]) {
          used[i] = true;
          return items[i];
       }
     }
     return null; // not reached
   }
   protected synchronized boolean markAsUnused(Object item) {
     for (int i = 0; i < MAX_AVAILABLE; ++i) {
       if (item == items[i]) {
          if (used[i]) {
            used[i] = false;
            return true;
          } else
            return false;
       }
     }
     return false;
   }
 }

For more java design pattern implementation object pool pattern examples related articles, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools