Throttling CPU/Memory usage of a Thread in Java?

前端 未结 9 2259
借酒劲吻你
借酒劲吻你 2020-12-07 13:00

I\'m writing an application that will have multiple threads running, and want to throttle the CPU/memory usage of those threads.

There is a similar question for C++,

9条回答
  •  暖寄归人
    2020-12-07 13:16

    If you run the threads in a separate process you can cap the memory usage and limit the number of CPUs or change the priority of these threads.

    However, anything you do is likely to add overhead and complexity which is often counter-productive.

    Unless you can explain why you would want to do this (e.g. you have a badly written library you don't trust and can't get support for) I would suggest you don't need to.

    The reason its not easy to restrict memory usage is there is only one heap which is shared. So an object which is used in one thread is usable in another and is not assigned to one thread or another.

    Limiting CPU usage means stopping all the threads so they don't do anything, however a better approach is to make sure the thread don't waste CPU and are only active doing work which needs to be done, in which case you wouldn't want to stop them doing it.

提交回复
热议问题