简体   繁体   English

Java:在这种情况下我应该使用多线程吗?

[英]Java: Should I use multithreading in this scenario?

I am writing a server side application using Java. 我正在使用Java编写服务器端应用程序。

The server holds a number of users of the system. 服务器拥有该系统的许多用户。 For each user, I want to synchronize its disk space with a remote network storage. 对于每个用户,我想将其磁盘空间与远程网络存储同步。 Because synchronizations are independent, I am thinking to do them concurrently. 因为同步是独立的,所以我想同时进行。

I am thinking to create one thread for each user and let the synchronization tasks to fire at the same time. 我正在考虑为每个用户创建一个线程,并让同步任务同时启动。

But the system can have tens of thousands of users. 但是系统可以有成千上万的用户。 This means creating tens of thousand thread at one time and fire at the same time. 这意味着一次创建数万个线程并同时触发。 I am not sure if this is something JVM can handle. 我不确定这是否是JVM可以处理的。

Even if it can handle this, will that be memory efficient because each thread have its own stack and this could be a big memory hit! 即使它可以处理此问题,也可以提高内存效率,因为每个线程都有自己的堆栈,这可能会造成很大的内存损失!

Please let me know your opinion. 请让我知道你的意见。

Many thanks. 非常感谢。

You could look at a fixed size thread pool giving a pool of threads to execute your task. 您可以查看一个固定大小的线程池,其中提供了一个线程池来执行您的任务。 This would give the benefit of multithreading with a sensible limit. 这将给多线程带来合理的限制。

Check out Executors.newFixedThreadPool() 签出Executors.newFixedThreadPool()

You should look into Non-blocking IO. 您应该研究非阻塞IO。

Here is a "random" article about it from courtesy of google: http://www.developer.com/java/article.php/3837316/Non-Blocking-IO-Made-Possible-in-Java.htm 这是Google提供的有关它的“随机”文章: http : //www.developer.com/java/article.php/3837316/Non-Blocking-IO-Made-Possible-in-Java.htm

Personally I wouldn't have tens of thousands of users on a single machine. 就个人而言,一台计算机上不会有成千上万的用户。 You won't be able to much per user with this many users active. 在这么多用户处于活动状态的情况下,每个用户将无法获得太多收益。 You should be able to afford more than one machine. 您应该能够负担多于一台机器。

You can have this many thread in Java but as you say this is not efficient. 您可以在Java中拥有这么多线程,但正如您所说的那样,效率不高。 You can use an NIO library to manage multiple connection with each thread. 您可以使用NIO库来管理每个线程的多个连接。

Libraries like 像图书馆

http://mina.apache.org/ http://mina.apache.org/

http://www.jboss.org/netty http://www.jboss.org/netty

Are suitable. 是合适的。

Also interesting http://code.google.com/p/nfs-rpc/ 同样有趣的http://code.google.com/p/nfs-rpc/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM