ThreadLocal,LinkedBlockingQueue,线程池 获取数据库连接2改进
package com.ctl.util; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit; import com.ctl.util.ConfigUtils;
import com.ctl.util.LogUtil; public class ThreadLocalBlockingQueueUtils {
private static ThreadLocal<LinkedBlockingQueue<Connection>> queueHoder = new ThreadLocal<LinkedBlockingQueue<Connection>>();
public static int num = 0;
private static String driver;
private static String url;
private static String username;
private static String password;
private static int threadPoolMaxNum; private static int threadPoolMinNum;
private static LogUtil log;
// \u6570\u636E\u5E93\u7C7B\u578Boracle mysql db2
private static String databasetype;
public static int getThreadPoolMaxNum() {
return threadPoolMaxNum;
} public static int getThreadPoolMinNum() {
return threadPoolMinNum;
} public static String getUrl() {
return url;
} public static String getUsername() {
return username;
} public static String getPassword() {
return password;
} static {
log = new LogUtil();
databasetype = ConfigUtils.getType("databasetype");
threadPoolMaxNum = Integer.parseInt(ConfigUtils
.getType("threadPoolMaxNum"));
threadPoolMinNum = Integer.parseInt(ConfigUtils
.getType("threadPoolMinNum"));
if (databasetype.equals("mysql")) {
driver = ConfigUtils.getType("mysql.driver");
url = ConfigUtils.getType("mysql.url");
username = ConfigUtils.getType("mysql.username");
password = ConfigUtils.getType("mysql.password");
} else if (databasetype.equals("oracle")) {
driver = ConfigUtils.getType("oracle.driver");
url = ConfigUtils.getType("oracle.url");
username = ConfigUtils.getType("oracle.username");
password = ConfigUtils.getType("oracle.password");
}
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
CreateConnection createConn = new CreateConnection();
createConn.setDaemon(true);
createConn.start();
} public static synchronized LinkedBlockingQueue<Connection> getQueue() {
LinkedBlockingQueue<Connection> queue = queueHoder.get();
if (queue == null) {
queue = new LinkedBlockingQueue<Connection>(threadPoolMaxNum);
queueHoder.set(queue);
return queue;
}
return queue;
} // static void start() {
// Tom tom = new Tom();
// tom.start();
// for(;;){
// try {
// Thread.sleep(200);
// System.out.println("/*************"+getConnection()+"*************/");
// } catch (InterruptedException e) {
// }
// }
// }
//
// public static void main(String[] args) {
// ThreadLocalBlockingQueueUtils.start();
// } public static Connection getConnection() {
// System.out.println("进入getConnection");
class GetConnectionClazz extends Thread {
LinkedBlockingQueue<Connection> queue = ThreadLocalBlockingQueueUtils
.getQueue();
private Connection conn;
private int queueSize;
public int getQueueSize() {
return queueSize;
}
public Connection getConn() {
return conn;
}
public synchronized void run() {
// System.out.println("进入getConnection run()");
try {
// System.err.println("-----"+conn+"--------");
while (conn == null) {// 非常重要没有该while循环当按F5不断刷新时,仅仅要有一个取出来为空后面的全为空
conn = queue.poll(2, TimeUnit.SECONDS);
}
queueSize=queue.size();
// System.err.println("*******"+conn+"*********");
// if (conn != null) {
// System.err.println("\u3010" + queue.size() + "\u3011"
// + "getConnecion\u6210\u529F\uFF1A" + conn);
// }
} catch (InterruptedException e) {
log.WriteLine("getConnection", e.getMessage());
}
}
}
GetConnectionClazz jj = new GetConnectionClazz();
jj.start();
try {
jj.join();
} catch (InterruptedException e) {
log.WriteLine("getConnection()", e.getMessage());
}
log.WriteLine("getConnection()","\u3010" + jj.getQueueSize() + "\u3011"+ "getConnecion\u6210\u529F\uFF1A" + jj.getConn());
return jj.getConn();
} } // class GG extends Thread {
// public void run() {
// for (;;){
// try {
// ThreadLocalBlockingQueueUtils.getConnection();
// Thread.sleep(300);
// } catch (Exception e) {
// }
// }
// }
// }
/**
* @descritpion 创建数据库连接的线程类
* @author Administrator
*
*/
class CreateConnection extends Thread {
LinkedBlockingQueue<Connection> queue = ThreadLocalBlockingQueueUtils
.getQueue();
LogUtil log = new LogUtil(); public synchronized void run() {
boolean result = false;
while (true) {
try {
Random rand=new Random();
int num=ThreadLocalBlockingQueueUtils.getThreadPoolMaxNum()-ThreadLocalBlockingQueueUtils.getThreadPoolMinNum();
int randSize=rand.nextInt(num)+1;
if(queue.size()>=randSize){
Thread.sleep(100);
continue;
}
Connection conn = null;
conn = DriverManager.getConnection(
ThreadLocalBlockingQueueUtils.getUrl(),
ThreadLocalBlockingQueueUtils.getUsername(),
ThreadLocalBlockingQueueUtils.getPassword());
if (conn != null) {
result = queue.offer(conn, 1, TimeUnit.SECONDS);
} else {
// System.out.println("DriverManager.getConnection is null");
log.WriteLine("CreateConnection.run()",
"DriverManager.getConnection()返回 null");
continue;
}
if (result == false) {
Thread.sleep(100);
log.WriteLine("CreateConnection.run()",
"已达到最大连接数queue.size()=" + queue.size());
// System.out.println("已经满了size=【" + queue.size() + "】");
} else {
log.WriteLine("CreateConnection.run()",
"\u3010" + queue.size() + "\u3011"
+ "createConnection success:" + conn);
// System.out.println("\u3010" + queue.size() + "\u3011"
// + "createConnection success:" + conn);
}
} catch (InterruptedException e) {
// e.printStackTrace();
log.WriteLine("getConnection", e.getMessage());
// System.err.println(e.getMessage());
} catch (SQLException e) {
log.WriteLine("getConnection", e.getMessage());
// e.printStackTrace();
// System.err.println(e.getMessage());
}
}
}
}
ThreadLocal,LinkedBlockingQueue,线程池 获取数据库连接2改进的更多相关文章
- ThreadLocal与线程池使用的问题
感谢博主的这篇分享,见 https://www.cnblogs.com/qifenghao/p/8977378.html 在今天的面试中,突然被考官问了这个问题,当时脱口而出的是 threadloca ...
- dbcp2连接池获取数据库连接Connection
一.先来看看手工创建的方式 public static Connection getConnection() { Connection conn = null; try { Class.forName ...
- 当ThreadLocal碰上线程池
ThreadLocal使用 ThreadLocal可以让线程拥有本地变量,在web环境中,为了方便代码解耦,我们通常用它来保存上下文信息,然后用一个util类提供访问入口,从controller层到s ...
- 源码分析—ThreadPoolExecutor线程池三大问题及改进方案
前言 在一次聚会中,我和一个腾讯大佬聊起了池化技术,提及到java的线程池实现问题,我说这个我懂啊,然后巴拉巴拉说了一大堆,然后腾讯大佬问我说,那你知道线程池有什么缺陷吗?我顿时哑口无言,甘拜下风,所 ...
- ThreadLocal遇到线程池时, 各线程间的数据会互相干扰, 串来串去
最近遇到一个比较隐蔽而又简单地问题,在使用ThreadLocal时发现出现多个线程中值串来串去,排查一番,确定问题为线程池的问题,线程池中的线程是会重复利用的,而ThreadLocal是用线程来做Ke ...
- python并发——从线程池获取返回值
并发是快速处理大量相似任务的绝佳办法,但对于有返回值的方法,需要一个容器专门来存储每个进程处理完的结果 from multiprocessing import Pool import time #返回 ...
- 线程池(Java中有哪些方法获取多线程)
线程池(Java中有哪些方法获取多线程) 前言 获取多线程的方法,我们都知道有三种,还有一种是实现Callable接口 实现Runnable接口 实现Callable接口 实例化Thread类 使用线 ...
- mysql 线程池 数据库连接池
当客户端请求的数据量比较大的时候,使用线程池可以节约大量的系统资源,使得更多的CPU时间和内存可以高效地利用起来.而数据库连接池的使用则将大大提高程序运行效率,同时,我们可以通过其自身的管理机制来监视 ...
- Java 中的几种线程池,你之前用对了吗
好久不发文章了,难道是因为忙,其实是因为懒.这是一篇关于线程池使用和基本原理的科普水文,如果你经常用到线程池,不知道你的用法标准不标准,是否有隐藏的 OOM 风险.不经常用线程池的同学,还有对几种线程 ...
随机推荐
- poj 3250 Bad Hair Day
Bad Hair Day Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 21084 Accepted: 7202 Des ...
- nginx进行项目域名配置时提示Job for nginx.service failed
ps aux | grep nginx /bin/systemctl stop nginx.service /bin/systemctl start nginx.service /bin/system ...
- SQL索引碎片整理脚本
原文发布时间为:2011-02-23 -- 来源于本人的百度文章 [由搬家工具导入] reindex是比较好的选择,速度快,但是他不能在线操作INDEXDEFRAG 比较慢,但是可以在线操作rebui ...
- 小甲鱼PE详解之资源(PE详解11)
原文出自:www.fishc.com 最近一直在安排第一届鱼C 学习班的事情,忙活了好一阵子,真是对不住大家,还大家久等了,这里要跟大家说声不好意思 ^_^ 今天我们来谈谈资源部分,资源部分可以说是 ...
- 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---42
以下为阅读<Linux命令行与shell脚本编程大全 第3版>的读书笔记,为了方便记录,特地与书的内容保持同步,特意做成一节一次随笔,特记录如下:
- JavaScript 之类型转换
数值转换成字符串类型 1.利用 “+” 将数值加上一个长度为零的空字符串. 2.通过toString()方法.加入参数可以直接进行进制的转换. <script language="ja ...
- Centos7 安装docker ce
一. 安装docker 1.升级rpm包 yum -y update 2. 通过命令设置Docker CE 资源库: yum install -y yum-utils yum-config-manag ...
- 51nod 1105 第K大的数 【双重二分/二分套二分/两数组任意乘积后第K大数】
1105 第K大的数 基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题 收藏 关注 数组A和数组B,里面都有n个整数.数组C共有n^2个整数,分别是A[0] * ...
- httpd安装和配置(cgi、wsgi)
参考:http://webpy.org/cookbook/mod_wsgi-apache.zh-cn 一.yum方式安装: 1.yum install httpd 输入y后继续. 2.看到一下类似的返 ...
- C++ 11中几个我比较喜欢的语法(二)
之前在文章C++ 11中几个我比较喜欢的语法中介绍了几个我比较喜欢的C++语法,其中有些语法由于VC 11还不支持,无法跨平台,所以没有介绍.前几天VS 2013 Preview发布后,对C++ 11 ...