java优化上传速度慢怎么办,限制Java的上传速度?

I'd like to programmatically limit an upload or download operation in Java. I would assume that all I'd need to do was do check how fast the upload is going and insert Thread.sleep() accordingly like so:

while (file.hasMoreLines()) {

String line = file.readLine();

for (int i = 0; i < line.length(); i+=128) {

outputStream.writeBytes(line.substr(i, i+128).getBytes());

if (isHittingLimit())

Thread.sleep(500);

}

}

Will the above code work? If not, is there a better way to do this? Is there a tutorial which describes the theory?

解决方案

Token Bucket Algorithm is a way to limit an upload or a download's bandwidth.

You should read this article : it explains the use of this algorithm.

// rate = 512 permits per second or 512 bytes per second in this case

final RateLimiter rateLimiter = RateLimiter.create(512.0);

while (file.hasMoreLines()) {

String line = file.readLine();

for (int i = 0; i < line.length(); i+=128) {

byte[] bytes = line.substr(i, i+128).getBytes();

rateLimiter.acquire(bytes.length);

outputStream.writeBytes(bytes);

}

}

As explained in Guava docs:

It is important to note that the number of permits requested never affects the throttling of the request itself (an invocation to acquire(1) and an invocation to acquire(1000) will result in exactly the same throttling, if any), but it affects the throttling of the next request. I.e., if an expensive task arrives at an idle RateLimiter, it will be granted immediately, but it is the next request that will experience extra throttling, thus paying for the cost of the expensive task.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值