Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.util.regex.Pattern;

import java.io.FileFilter;

public class Main {

    public static int getCPUCores() {
        //Strategy 1.
        //The value may less than real value.
        //int cores_runtime = Runtime.getRuntime().availableProcessors();

        //Strategy 2.
        int cores = 1;
        class CpuFilter implements FileFilter {
            @Override
            public boolean accept(File pathname) {
                return Pattern.matches("cpu[0-9]", pathname.getName());
            }
        }
        try {
            File dir = new File("/sys/devices/system/cpu/");
            File[] files = dir.listFiles(new CpuFilter());
            cores = files.length;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cores;
    }
}