首页 文章 精选 留言 我的

精选列表

搜索[Rust编程],共10000篇文章
优秀的个人博客,低调大师

Java并发编程-撸一个数据库连接池

章节目录 等待超时模式的使用场景 可以掌握的技能 等待/通知 消费者/生产者模式 CountDownLatch、AtomicInteger、静态内部类、LinkedList、动态代理的使用 1.等待超时模式 场景 当我们调用方法时,这个方法返回的资源比较重要,比如获取数据库连接池中连接句柄。但是这个资源的返回随着业务量的增加,那么获取资源(连接池连接)的时间就会增加,那么调用一个方法时就要等待一段时间(一般来说是给定一个时间段),如果该方法能够在一段时间内获取到结果,那么将结果立刻返回,反之,超时返回默认结果。 等待/通知的经典范式,即加锁、条件循环、处理逻辑3个步骤,这种范式没办法做到超时等待,对经典范式做很小的改动,就可以实现超时等待。 等待超时模式伪代码: public synchronized Object get(long mills) throws InterruptedException { Object result = null; long future = System.currentTimeMills() + mills; long remaining = mills; while (result == null && remaining > 0) { wait(remaining);//释放锁,阻塞 mills 毫秒 remaining = future - System.currentTimeMills(); } return result;//如果超时之后获取到result则不返回null } 超时等待的作用就是不会永远阻塞调用者,但是 超时之后被唤醒,知识将线程从等待队列移动至阻塞队列,继续向下进行返回result还是要重新获取锁,如果一直获取不到锁,那么result也不会打印。只是增加了灵活性。 2.可以掌握的技能 实战 使用等待超时模式撸一个简单数据库连接池,在示例中模拟: 从连接池获取连接 RunnerThread 使用连接 RunnerThread 释放连接 RunnerThread注意:客户端获取(消费)连接的过程被设定为等待超时、等待/通知两种模式ConnectionPool.java-数据库连接池 package org.seckill.DBConnection; import java.sql.Connection; import java.util.LinkedList; /** * 数据库连接池对象 */ public class ConnectionPool { //链表list(池)维护 connection 连接对象 private LinkedList<Connection> pool = new LinkedList<Connection>(); //构造方法 初始化池中连接 public ConnectionPool(int initialSize) { if (initialSize > 0) { for (int i = 0; i < initialSize; i++) { pool.addLast(ConnectionDriver.createConnection());//创建initialSize个代理Connection对象 } } } //释放connection ,相当于-生产者 public void releaseConnection(Connection connection) { if (connection != null) {//有效归还连接 synchronized (pool) { pool.addLast(connection); //生产者动作完毕后,需要唤醒所有消费者 pool.notifyAll(); } } } //获取connection句柄,相当于消费者,采用超时等待与等待/通知两种策略 public Connection fetchConnection(long mills) throws InterruptedException { synchronized (pool) { if (mills < 0) {//非超时等待模式,采用等待/通知模式 while (pool.isEmpty()) { pool.wait();//本示例中不演示这种模式下获取连接的情景 } return pool.removeFirst(); } else {//超时等待模式 long future = System.currentTimeMillis() + mills; long remaining = mills; while (pool.isEmpty() && remaining > 0) { pool.wait(remaining); remaining = future - System.currentTimeMillis(); } Connection connection = null; if (!pool.isEmpty()) { connection = pool.removeFirst();//返回头结点对象 } return connection; } } } } ConnectionDriver.java-动态生成Connection代理对象 package org.seckill.DBConnection; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; /** * 数据库连接驱动, * 动态代理获取实现java.sql.Connection 接口的代理对象 */ public class ConnectionDriver { static class ConnectionHandler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName() == "commit") { Thread.sleep(100); } return null; } } //获取Connection的动态代理类 public static final Connection createConnection() { return (Connection) Proxy.newProxyInstance( ConnectionDriver.class.getClassLoader(),//类加载器 new Class<?>[]{Connection.class},//Connection实现的接口列表,包含Connection接口 new ConnectionHandler());//与代理对象绑定的handler } } ConnectionPoolTest.java--测试类 package org.seckill.DBConnection; import java.sql.Connection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; public class ConnectionPoolTest { //线程池中初始化10个连接 static ConnectionPool connectionPool = new ConnectionPool(10); //保证所有的ConnectionRunner 能够同时开始 static CountDownLatch start = new CountDownLatch(1); //main线程将等待所有的Connection Runner结束后才开始执行 static CountDownLatch end; public static void main(String[] args) throws Exception { //ConnectionRunner 线程数量,可以修改线程数量进行观察 int threadCount = 50; end = new CountDownLatch(threadCount); int count = 20;//每个线程进行20次fetchConnetion动作 AtomicInteger got = new AtomicInteger(); AtomicInteger notGot = new AtomicInteger(); for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(new ConnectionRunner(count, got, notGot), "ConnectionRunnerThread"); thread.start(); } start.countDown();//使所有线程同时运行 end.await();//主线程等待所有线程运行完 System.out.println("总的请求次数" + threadCount * count); System.out.println("获取到的连接总数" + got); System.out.println("未获取到的连接总数" + notGot); } static class ConnectionRunner implements Runnable { int count;//每个线程fetchConnetion的次数 AtomicInteger got;//记录fetchConnection 成功的次数 AtomicInteger notGot;//记录fetchConnetion 未成功的次数 public ConnectionRunner(int count, AtomicInteger got, AtomicInteger notGot) { this.count = count; this.got = got; this.notGot = notGot; } public void run() { try { start.await();//等待 所有ConnectionRunner 初始化成功且处于Runnable状态,同时开始运行,由主线程控制的 } catch (InterruptedException e) { e.printStackTrace(); } while (count > 0) { try { //从连接池中获取连接,如果1000ms内无法获取到,将会返回null。 Connection connection = connectionPool.fetchConnection(1000); if (connection != null) { try { connection.createStatement(); connection.commit(); } finally { //归还连接 connectionPool.releaseConnection(connection); got.incrementAndGet();//对获取次数状态进行更改 } } else { notGot.incrementAndGet();//对未获取次数状态进行更改 } } catch (Exception e) { } finally { count--;//运行次数递减 } } end.countDown(); } } } 运行结果 1.设置RunnerConnection threadCount数为10 threadCount = 10 2.设置RunnerConnection threadCount数为20 threadCount = 20 3.设置RunnerConnection threadCount数为50 threadCount = 50 4.设置RunnerConnection threadCount数为100 threadCount = 50 可以看到随着 runnerConnection 连接线程数的递增,连接的稳定性是越来越低的。但用户调用不会长时间阻塞到connect fetch 上,而是按时返回。

优秀的个人博客,低调大师

<Java多线程编程核心技术>讲解得太细致啦

一个synchronized关键字,能讲一百多页,搞出几十个小举例。 我是服了! 但真的一路演练一下, 对这个关键的应用场景还是了解了很多的。 package test; public class Service { private boolean isContinueRun = true; public void runMethod() { String anyString = new String(); while (isContinueRun == true) { synchronized (anyString){ } } System.out.println("have stopped."); } public void stopMethod() { isContinueRun = false; } } package test; public class ThreadA extends Thread { private Service service; public ThreadA(Service service) { super(); this.service = service; } @Override public void run() { service.runMethod(); } } package test; public class ThreadB extends Thread { private Service service; public ThreadB(Service service) { super(); this.service = service; } @Override public void run() { service.stopMethod(); } } package test; public class Run { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub try { Service service = new Service(); ThreadA a = new ThreadA(service); a.start(); Thread.sleep(1000L); ThreadB b = new ThreadB(service); b.start(); System.out.println("have set stop order."); } catch (InterruptedException e) { e.printStackTrace(); } } }

优秀的个人博客,低调大师

iOS多线程编程之多社交平台同步推送的设计与实现

功能介绍 在开发快易博的时候,有一个功能叫做“分享心情”【见下图】。它的主要功能是:用户可以一次发表一个微博(在人人网称之为新鲜事)到所有用户选择的绑定平台(其实就是通常所说的微博同步)。 进入之后: 这个功能实现起来并不难,说白了就是依次调用各个开放平台的关于“发表”相关的API就好了。但牵扯到几个给用户提供更好的“用户体验”的需求,就不得不使用多线程了,需求如下: (1) 在图二对应的功能界面上,用户在发表完成之后,应该可以立即关闭; (2) 在各个平台的独立发表界面,在发表完成之后,发表界面自动关闭,显示打开发表界面之前的一个界面。 注:分享心情界面其实实现的是一个多功能的发表界面,可以同步推送,也可以选择你想推送的平台。为了给用户提供方便,在你点进各个平台之后(比如新浪微博),它里面有单独的发表到该平台的发表界面来提供更多的功能,比如“@、##”等,见下图。 原先的处理方式 对于上面的需求(1),我原先的做法是,在用户点击右上角的发表按钮之后。用MBProgressHUD强制给当前界面设置一个“遮罩”,以让返回按钮不可点击。这样做的目的是为了停留在当前界面来等待执行各个开放平台提供的诸如“发表成功”、“发表失败”之类的回调协议,并且在回调协议里,通过在状态栏使用提示信息来提示用户是否成功。 假如让返回按钮可点击,用户有可能在发表完成之后立马选择返回,那么当前的UIViewController可能已经被释放,回调的时候就会导致应用崩溃。当然如果用MBProgressHUD hold主整个界面,用户除了选择等待就没有别的选择,而回调协议执行的时机其实取决于很多不确定因素(比如当前的网速,如果附带了图片,还要看图片的大小,以及各个开放平台对于API调用的响应速度等等),可能很快,也可能会等个好几十秒。而一旦你考验用户的耐心,那就是在给自己埋定时炸弹了。 对于需求(2),比需求(1)的关闭速度更快。我需要让用户在发表完成之后,发表界面立即关闭。所以当前UIViewController根本等不到回调协议的调用就已经释放,状态栏提示也无法实现。当然,妥协的办法还是用MBProgressHUD显示个“请稍后…”之类的强制让界面无法响应用户,等回调完成在选择关闭。 现在的处理方式 从上面的分析可以看得出,我希望回调协议与当前发表界面的UIViewController对象的生命周期没有关系。那么只能让这些“发表”操作都不在主线程(UI线程)上执行,这也就实现了发表操作与发表功能界面的解耦。 设计与代码实现 在iOS中实现多线程的方式有几种,这里使用NSOperation以及NSOperationQueue来实现。 UML简图: 大致代码如下: PublishOperation: #import <Foundation/Foundation.h> #import "MTStatusBarOverlay.h" @interface PublishOperation : NSOperation < MTStatusBarOverlayDelegate > @property (nonatomic,copy) NSString* txt; @property (nonatomic,copy) NSString *publishImgPath; @property (nonatomic,assign) BOOL completed; @property (nonatomic,assign) BOOL canceledAfterError; @property (nonatomic,retain) MTStatusBarOverlay *overlay; - (void)clearPublishedImage; - (id)initWithOperateParams:(NSString*)content; @end #import "PublishOperation.h" @implementation PublishOperation @synthesize completed; @synthesize canceledAfterError; @synthesize txt=_txt; @synthesize overlay=_overlay; @synthesize publishImgPath=_publishImgPath; - (void)dealloc{ [_txt release],_txt=nil; [_overlay release],_overlay=nil; [_publishImgPath release],_publishImgPath=nil; [super dealloc]; } - (id)init{ if (self=[super init]) { completed=NO; canceledAfterError=NO; [self initMTStatusBarOverlay]; } return self; } - (id)initWithOperateParams:(NSString*)content{ if (self=[self init]) { self.txt=content; } return self; } /* *实例化工具栏提示组件 */ -(void)initMTStatusBarOverlay{ _overlay = [MTStatusBarOverlay sharedInstance]; _overlay.animation = MTStatusBarOverlayAnimationFallDown; _overlay.detailViewMode = MTDetailViewModeHistory; _overlay.delegate=self; } - (void)main{ //操作既没有完成也没有因为发生错误而取消,则hold住当前run loop //防止返回主线程使得代理方法无法执行 while (!(self.completed||self.canceledAfterError)) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; DebugLog(@"running!"); } } #pragma mark - other methods - - (void)clearPublishedImage{ //清除緩存圖片 if (fileExistsAtPath(self.publishImgPath)) { removerAtItem(self.publishImgPath); } } @end SinaWeiboPublishOperation #import "PublishOperation.h" #import "WBEngine.h" @interface SinaWeiboPublishOperation : PublishOperation < WBEngineDelegate > @end #import "SinaWeiboPublishOperation.h" @interface SinaWeiboPublishOperation() @property (nonatomic,retain) WBEngine *engine; @end @implementation SinaWeiboPublishOperation @synthesize engine=_engine; - (void)dealloc{ [_engine setDelegate:nil]; [_engine release],_engine=nil; [super dealloc]; } /* *business logic */ - (void)main{ self.publishImgPath=PUBLISH_IMAGEPATH_SINAWEIBO; _engine = [[WBEngine alloc]initWithAppKey:kWBSDKDemoAppKey appSecret:kWBSDKDemoAppSecret]; _engine.delegate=self; [self.engine sendWeiBoWithText:self.txt image:[UIImage imageWithContentsOfFile: PUBLISH_IMAGEPATH_SINAWEIBO]]; [self.overlay postImmediateMessage:@"新浪微博发表中..." animated:YES]; [super main]; } #pragma mark - WBEngineDelegate Methods - - (void)engine:(WBEngine *)engine requestDidSucceedWithResult:(id)result{ [self clearPublishedImage]; [GlobalInstance showOverlayMsg:@"新浪微博发表成功!" andDuration:2.0 andOverlay:self.overlay]; self.completed=YES; [NSThread sleepForTimeInterval:5]; } - (void)engine:(WBEngine *)engine requestDidFailWithError:(NSError *)error{ [self clearPublishedImage]; [GlobalInstance showOverlayErrorMsg:@"新浪微博发表失败!" andDuration:2.0 andOverlay:self.overlay]; self.canceledAfterError=YES; [NSThread sleepForTimeInterval:5]; } RenRenPublishOperation #import "PublishOperation.h" @interface RenRenPublishOperation : PublishOperation < RenrenDelegate > @end #import "RenRenPublishOperation.h" @implementation RenRenPublishOperation /* *business logic */ - (void)main{ self.publishImgPath=PUBLISH_IMAGEPATH_RENREN; BOOL hasImage=[[NSFileManager defaultManager]fileExistsAtPath:PUBLISH_IMAGEPATH_RENREN]; if (hasImage) { ROPublishPhotoRequestParam *photoParams=[[[ROPublishPhotoRequestParam alloc]init]autorelease]; photoParams.imageFile=[UIImage imageWithContentsOfFile:PUBLISH_IMAGEPATH_RENREN]; photoParams.caption=self.txt; [[Renren sharedRenren] publishPhoto:photoParams andDelegate:self]; [self.overlay postImmediateMessage:@"人人图片上传中..." animated:YES]; }else { NSMutableDictionary *params=[NSMutableDictionary dictionaryWithCapacity:10]; [params setObject:@"status.set" forKey:@"method"]; [params setObject:self.txt forKey:@"status"]; [[Renren sharedRenren]requestWithParams:params andDelegate:self]; [self.overlay postImmediateMessage:@"人人状态发表中..." animated:YES]; } [super main]; } #pragma mark - RenrenDelegate (ren ren) - -(void)renren:(Renren *)renren requestDidReturnResponse:(ROResponse *)response{ [self clearPublishedImage]; [GlobalInstance showOverlayMsg:@"人人新鲜事发表成功!" andDuration:2.0 andOverlay:self.overlay]; self.completed=YES; [NSThread sleepForTimeInterval:5]; } TencentWeiboPublishOperation #import "PublishOperation.h" #import "TencentWeiboDelegate.h" @interface TencentWeiboPublishOperation : PublishOperation < TencentWeiboDelegate > @end #import "TencentWeiboPublishOperation.h" #import "TencentWeiboManager.h" #import "OpenApi.h" @implementation TencentWeiboPublishOperation /* *business logic */ - (void)main{ [self.overlay postImmediateMessage:@"腾讯微博发表中..." animated:YES]; self.publishImgPath=PUBLISH_IMAGEPATH_TENCENTWEIBO; BOOL hasImage=[[NSFileManager defaultManager]fileExistsAtPath:PUBLISH_IMAGEPATH_TENCENTWEIBO]; OpenApi *myApi=[TencentWeiboManager getOpenApi]; myApi.delegate=self; if (!hasImage) { [myApi publishWeibo:self.txt jing:@"" wei:@"" format:@"json" clientip:@"127.0.0.1" syncflag:@"0"]; }else{ [myApi publishWeiboWithImageAndContent:self.txt jing:@"" wei:@"" format:@"json" clientip:@"127.0.0.1" syncflag:@"0"]; } } #pragma mark - tencent weibo delegate - - (void)tencentWeiboPublishedSuccessfully{ [self clearPublishedImage]; [GlobalInstance showOverlayMsg:@"腾讯微博发表成功!" andDuration:2.0 andOverlay:self.overlay]; [NSThread sleepForTimeInterval:5]; } - (void)tencentWeiboRequestFailWithError{ [self clearPublishedImage]; [GlobalInstance showOverlayErrorMsg:@"腾讯微博发表失败!" andDuration:2.0 andOverlay:self.overlay]; [NSThread sleepForTimeInterval:5]; } @end 注解:NSOperation在非并发的执行方式下,只需要重新实现它的main方法即可。 在PublishOperation的main方法中的那段代码的主要目的hold主当前的RunLoop(通俗一点讲其实就是阻塞当前执行的上下文,直到回调协议被执行),由此可见这里仍然存在回调协议无法执行的问题。为什么会出现这种情况,为什么要hold执行的上下文?因为各个平台的API通常都是异步发送请求的(腾讯微博除外),等到有响应了再来执行实现了的协议。而所谓的异步,其实也是操作系统在后台用另一个线程来处理的。而NSOperation的执行模式是它执行完实现在main方法里的逻辑就会退出,返回主线程。所以通常情况下这里的回调协议还是没有得到机会执行(机会其实是得到了,只是当前的NSOperation对象已被释放,导致内存访问错误)。所以这里用一个while循环hold主当前的runloop,一直保持到各个平台的异步回调完协议之后,设置completed或者canceledAfterError为YES,以退出while循环。注意这两个属性是异步设置的,也就是说是另一个线程来设置的。这里说明一下,在各个平台调用了[super main];方法之后,其实你不在回调协议中(或者说在另一个线程中)是无法设置这两个属性的。因为[super main];这句让当前执行NSOperation的线程阻塞了。 我顺便吐槽一下腾讯微博开放平台,它们开放的Framework中,发出的请求居然是同步获取结果的,而且它们居然都没有定义任何的回调协议,这里也让我很费神。所以在TencentWeiboOperation中的实现会跟新浪、人人有所不同。因为调用是同步的,所以在TencentWeiboPublishOperation最后直接调用[super main];是没用的(因为它会在回调协议之后才会执行,所以这边不需要调用它) ,这边调用线程的Sleep方法,让线程睡眠5秒钟,也就是延迟当前的NSOperation上下文5秒,延迟是因为在状态栏显示提示信息需要2秒,如果不延迟,那么在completed设置为YES之后NSOperation就会执行完成并退出,那MTStatusOverlayDelegate也没有机会执行。 /* *状态栏显示完成提示信息 */ -(void)showOverlayMsg:(NSString*)msg andDuration:(NSTimeInterval)duration andOverlay:(MTStatusBarOverlay*)overlay{ [overlay postImmediateFinishMessage:msg duration:duration animated:YES]; } 你在应用程序的AppDelegate中定义一个NSOperationQueue,用来执行NSOperation,就可以完成对发表操作与发表功能界面的Controller解耦。这样就可以在发表完成之后,直接关闭并释放Controller,并且由于功能的封装,它变成一个独立的、可复用的整体。在“分享心情”功能界面里,多平台同步推送的话,你只需要把各个平台的“PublishOperation”丢到NSOperationQueue去,其他就不用管,直接关闭或者返回即可。 新浪微博单独发表界面示例代码: - (void)publishBtn_handle:(id)sender{ NSString *txt=self.publishTxtView.text; PublishOperation *publishOperation=[[[SinaWeiboPublishOperation alloc]initWithOperateParams:txt]autorelease]; [((FastEasyBlogAppDelegate*)appDelegateObj).operationQueue addOperation:publishOperation]; [self dismissModalViewControllerAnimated:YES]; } 分享心情发表界面示例代码: /* *发送 */ -(void)publish_click{ //移除高亮效果 UIButton *btn=(UIButton*)self.navigationItem.rightBarButtonItem.customView; [btn setBackgroundImage:[UIImage imageNamed:@"publishBtn.png"] forState:UIControlStateNormal]; if ([self.publishTxtView.text length]==0) { [GlobalInstance showMessageBoxWithMessage:@"请说点什么吧!"]; return; } NSString *weiboTextContent=self.publishTxtView.text; if (plaformSwitch.isRenRenOpen) { PublishOperation *renrenOperation=[[[RenRenPublishOperation alloc]initWithOperateParams:weiboTextContent]autorelease]; [((FastEasyBlogAppDelegate*)appDelegateObj).operationQueue addOperation:renrenOperation]; } if (plaformSwitch.isTencentWeiboOpen) { PublishOperation *tencentOperation=[[[TencentWeiboPublishOperation alloc]initWithOperateParams:weiboTextContent]autorelease]; [((FastEasyBlogAppDelegate*)appDelegateObj).operationQueue addOperation:tencentOperation]; } //清空內容 [self clearInputFromTextView]; UIButton *imgBtn=(UIButton*)[self.view viewWithTag:4321]; [imgBtn removeFromSuperview]; [self dismissModalViewControllerAnimated:YES]; } 最后,为自己打个广告: 这是本人的第一个“个人iOS应用”,它是一款能够帮助你同时在多个社交平台和好友沟通交流以及分享的应用。支持一键发表状态/心情/照片到所有绑定平台,快速浏览/回复/分享,以及多终端同时在线浏览好友微博与好友互动,为你提供更为便捷的社交体验。 原文发布时间为:2012-11-18 本文作者:vinoYang 本文来自云栖社区合作伙伴CSDN博客,了解相关信息可以关注CSDN博客。

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码