How many threads should I use in my Java program?

前端 未结 7 1309
日久生厌
日久生厌 2020-12-09 18:03

I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The ori

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 18:47

    Yes, that's a perfectly reasonable approach. One thread per processor/core will maximize processing power and minimize context switching. I'd probably leave that as-is unless I found a problem via benchmarking/profiling.

    One thing to note is that the JVM does not guarantee availableProcessors() will be constant, so technically, you should check it immediately before spawning your threads. I doubt that this value is likely to change at runtime on typical computers, though.

    P.S. As others have pointed out, if your process is not CPU-bound, this approach is unlikely to be optimal. Since you say these threads are being used to generate images, though, I assume you are CPU bound.

提交回复
热议问题