您的位置:首页 > 数据库

线程局部类控制数据库连接

2014-02-21 10:02 405 查看
最近一直在写关于大数据的批量处理,需要从数据库查出来 并且做出相应的处理,最少5万条 最多十几万条,对数据库的操作可以说是相当快的,一个select语句就可以解决问题,但是主要麻烦于数据取出来处理比较慢,用java单条主线程执行5万条数据用时5个小时,如果数据大了,业务负责了,有时候甚至会执行一天,显然是不可取的。所以第一时间想到的就是采取多线程,但是考虑的线程的管理 就决定使用线程池来控制,但是 使用线程来控制又遇到个新的问题,就是对Connection的管理,我写的东西的业务需要大量的操作数据库,有时候一个业务需要操作好几次数据库,于是决定每条线程执行一次业务时开启一个Connection连接,这样是解决了问题,但是突然感觉这样使用Connection有点浪费,每次连接都能使用上万次,并且create和close都是需要时间的,于是就想让一个线程多次执行业务尽量使用一个Connection。于是就想到了java自带的线程局部控制类ThreadLocal
然后就琢磨写了个 一下类测试,发现效率的确有所提升。

package threadLocal;

import java.sql.Connection;

import java.util.HashMap;

import java.util.Map;

/**

 * 线程局部测试

 * @author lizh

 * @date  2014-2-21上午9:49:47

 * @fileName ThreadLocalTest.java

 * @package threadLocal

 * @project Test

 */

public class ThreadLocalTest {

 private static ThreadLocal<Connection> local = new ThreadLocal<Connection>();

 private static Map<Integer, Conn> map = new HashMap<Integer, Conn>();

 private static final long TIME = 300000;//过期时间5分种

 private static final int COUNT = 10000;//过期次数

 public static Connection getStr(){

  if(local.get()==null){

   local.set(getConnection());

   map.put(local.get().hashCode(), new Conn(System.currentTimeMillis(), 0));

  }else{

   Conn c = map.get(local.get().hashCode());

   if(System.currentTimeMillis()-c.time>=TIME||c.count>=COUNT){

    map.remove(local.get().hashCode());

    local.set(getConnection());

    map.put(local.get().hashCode(), new Conn(System.currentTimeMillis(), 0));

   }else{

    Conn c1 = map.get(local.get().hashCode());

    c1.count=c1.count+1;

    map.put(local.get().hashCode(),c1);

   }

  }

  System.out.println("时间"+(System.currentTimeMillis()-(map.get(local.get().hashCode()).time)));

  System.out.println("次数"+map.get(local.get().hashCode()).count);

  return local.get();

 }

 public static Connection getConnection(){

  return null;

 }

 static class Conn{

  

  public Conn(long time, int count) {

   this.time = time;

   this.count = count;

  }

  long time;

  int count;

 }

}

代码写的可能不严谨,仅此表示一种想法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: