什么是粗略的“成本” CPU周期和内存中的线程? [英] What is the rough "Cost" of a Thread in CPU cycles and memory?

查看:111
本文介绍了什么是粗略的“成本” CPU周期和内存中的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中使用线程的粗略成本是多少?是拇指/经验值的任何规则,一个线程的创建需要多少内存?是否粗略估计创建线程需要多少CPU周期?

What is the rough "cost" of using threads in java? Are the any rule of thumbs/empirical values, how much memory the creation of one thread costs? Is there a rough estimate how many CPU cycles it costs to create a thread?

上下文:在Web应用程序的servlet中,我希望并行化内容创建,因为内容的一部分是基于文件的,基于数据库的以及基于Web服务的。但这意味着对于每个http-request-thread(我的serlvet容器),我将有两到四个额外的线程。请注意,我将在Java 6中使用 ExecutorService

Context: In a servlet of a webapplication I want to parallelize the content creation as parts of the content are file based, database based as well as webservices based. But this would mean that for every "http-request-thread" (of my serlvet container) I will have two-to-four additional threads. Note that I will be using the ExecutorService in Java 6.

当我使用数百到数千时,我应该期待什么? Web服务器上的Java线程?

What should I expect when I use hundreds to thousands of Java threads on a web-server?

推荐答案

每个线程都有自己的堆栈,因此会立即产生内存影响。对于Java 6,512k,默认线程堆栈大小为IIRC(不同的JVM /版本可能具有不同的默认值)。可以使用 -Xss 选项调整此数字。因此,使用数百个线程会对VM消耗的内存产生影响(很可能在任何CPU影响之前,除非这些线程正在运行)。

Each thread has its own stack, and consequently there's an immediate memory impact. The default thread stack size is ,IIRC, for Java 6, 512k (different JVMs/version will possibly have different defaults). This figure is adjustable using the -Xss option. Consequently using hundreds of threads will have an impact on the memory the VM consumes (quite possibly before any CPU impact unless those threads are running).

我见过客户端运行与线程/内存相关的问题,因为它不是一个明显的链接。创建100,000个线程(使用执行程序/池等)是微不足道的,并且内存问题似乎不会立即归因于此。

I've seen clients run into problems related to threads/memory, since it's not an obvious link. It's trivial to create 100,000 threads (using executors/pools etc.) and memory problems don't appear to be immediately attributable to this.

如果您为许多客户提供服务,您可能需要查看Java NIO API,特别是多路复用,允许异步网络编程。这将允许您只使用一个线程处理许多客户端,从而减少对大量线程的需求。

If you're servicing many clients, you may want to take a look at the Java NIO API and in particular multiplexing, which allows asynchronous network programming. That will permit you to handle many clients with only one thread, and consequently reduce your requirement for a huge number of threads.

这篇关于什么是粗略的“成本” CPU周期和内存中的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆