JVM Runtime.getRuntime().availableProcessors() returns 1 on AWS ECS Fargate

public class Example {
   public static void main(String[] args) {
      // print statement at the start of the program
      System.out.print("Number of available processors are: ");
      System.out.println( Runtime.getRuntime().availableProcessors());

Ref: https://www.tutorialspoint.com/get-number-of-available-processors-in-java

When I compile and run this code on AWS ECS Fargate getting "1" as the output even though I have specified more than 1 cpu in task def(4098 for 4 vCPU).

Tested Java versions:

  • Corretto-
  • Corretto-

But when I do the same on AWS EC2 inside docker by allocating CPU with --cpus for "docker run" I get the exact number what I pass to --cpus. Same results with AWS EC2 with Containerd as well.

Also tested this in EKS 1.18 by setting CPU limit. It returns the number of CPUs specified in the CPU limit.

So, wondering why "1" only in AWS ECS.

1개 답변

Hi, Good Question

As per https://www.databasesandlife.com/java-docker-aws-ecs-multicore/

There is no way to get Java to automatically use find out many cores are available and use them all, on AWS ECS using Docker. You have to specify how many cores you want to use via the -XX:ActiveProcessorCount option

I think you would have to use Threads in Java in order to use all cores https://gist.github.com/adrianmsmith/10be72c62c8dd292aeca9c34346bd3ea

In my case, the Runtime.getRuntime().availableProcessors() call was returning 1, even on my expensive multi-core server. Therefore only one thread was started, and all my code ran sequentially, even though multiple cores were available (and would have been used if the threads had been started.)

profile picture
답변함 2년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠