How do I get the number of processors available to the JVM?

The Runtime.getRuntime().availableProcessors() method returns the maximum number of processors available to the Java virtual machine, the value will never be smaller than one. Knowing the number of available processor you can use it for example to limit the number of thread in your application when you are writing a multi-thread code.

package org.kodejava.lang;

public class NumberProcessorExample {
    public static void main(String[] args) {
        final int processors = Runtime.getRuntime().availableProcessors();
        System.out.println("Number of processors = " + processors);
    }
}

Running the code snippet give you something like:

Number of processors = 8

How do I get all annotations?

To obtains all annotations for classes, methods, constructors, or fields we use the getAnnotations()method. This method returns an array of Annotation

In the following example we tried to read all annotations from the sayHi() method. First we need to obtain the method object itself. Because the sayHi() method has parameters, we need to pass not only the method name to the getMethod() method, but we also need to pass the parameter’s type.

The getAnnotations() method returns only annotation that has a RetentionPolicy.RUNTIME, because other retention policy doesn’t allow the annotation to available at runtime.

package org.kodejava.lang.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class GetAllAnnotation {
    private final Map<String, String> data = new HashMap<>();

    public static void main(String[] args) {
        GetAllAnnotation demo = new GetAllAnnotation();
        demo.sayHi("001", "Alice");
        demo.sayHi("004", "Malory");

        try {
            Class<? extends GetAllAnnotation> clazz = demo.getClass();

            // To get the sayHi() method we need to pass not only the method
            // name but also its parameters type so the getMethod() method
            // return the correct method for us to use.
            Method method = clazz.getMethod("sayHi", String.class, String.class);

            // Get all annotations from the sayHi() method. But this actually
            // will only return one annotation. Because only the HelloAnnotation
            // annotation that has RUNTIME retention policy, which means that
            // the other annotations associated with sayHi() method is not
            // available at runtime.
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println("Type: " + annotation.annotationType());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @MyAnnotation("Hi")
    @HelloAnnotation(value = "Hello", greetTo = "Everyone")
    public void sayHi(String dataId, String name) {
        Map<String, String> data = getData();
        if (data.containsKey(dataId)) {
            System.out.println("Hello " + data.get(dataId));
        } else {
            data.put(dataId, name);
        }
    }

    private Map<String, String> getData() {
        data.put("001", "Alice");
        data.put("002", "Bob");
        data.put("003", "Carol");
        return data;
    }
}
package org.kodejava.lang.annotation;

public @interface MyAnnotation {
    String value();
}

Check the HelloAnnotation on the following link How do I create a simple annotation?.

The result of this code snippet:

Hello Alice
Type: interface org.kodejava.lang.annotation.HelloAnnotation

How do I execute external command and obtain the result?

This example demonstrate how to execute an external command from Java and obtain the result of the command. Here we simply execute a Linux ls -al command on the current working directory and display the result.

package org.kodejava.lang;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ProcessResult {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("ls -al");

            // Wait for this process to finish or terminated
            process.waitFor();

            // Get process exit value
            int exitValue = process.exitValue();
            System.out.println("exitValue = " + exitValue);

            // Read the result of the ls -al command by reading the
            // process's input stream
            InputStreamReader is = new InputStreamReader(process.getInputStream());
            BufferedReader reader = new BufferedReader(is);
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Below is our program result:

exitValue = 0
total 64
drwxr-xr-x  20 wsaryada  staff   680 Aug  7 14:13 .
drwxr-xr-x   4 wsaryada  staff   136 Jun 18 00:33 ..
-rw-r--r--@  1 wsaryada  staff  6148 Jun 29 14:04 .DS_Store
-rw-r--r--   1 wsaryada  staff   267 May 19 20:47 .editorconfig
drwxr-xr-x  16 wsaryada  staff   544 Aug 10 08:34 .git
-rw-r--r--   1 wsaryada  staff  1535 May 19 20:47 .gitignore
drwxr-xr-x  15 wsaryada  staff   510 Aug 10 08:34 .idea
-rw-r--r--   1 wsaryada  staff  1313 May 19 20:47 LICENSE
-rw-r--r--   1 wsaryada  staff   101 May 19 20:47 README.md
drwxr-xr-x   5 wsaryada  staff   170 Jul 28 23:11 kodejava-basic
drwxr-xr-x   6 wsaryada  staff   204 Jun 30 14:22 kodejava-commons
drwxr-xr-x   6 wsaryada  staff   204 Jul 27 15:32 kodejava-lang-package
drwxr-xr-x@  5 wsaryada  staff   170 Jun 16 20:49 kodejava-mail
drwxr-xr-x   6 wsaryada  staff   204 Aug  7 17:22 kodejava-mybatis
drwxr-xr-x   5 wsaryada  staff   170 Jul 20 10:36 kodejava-poi
-rw-r--r--   1 wsaryada  staff   669 Jun  2 14:29 kodejava-project.iml
drwxr-xr-x   7 wsaryada  staff   238 Jun 26 21:52 kodejava-swing
drwxr-xr-x   6 wsaryada  staff   204 Aug  3 15:06 kodejava-util-package
drwxr-xr-x   6 wsaryada  staff   204 Jun 30 15:09 maven-helloworld
-rw-r--r--   1 wsaryada  staff  1622 Aug  7 14:13 pom.xml

How do I know the memory size in virtual machine?

If you want to know the free memory, and the total memory available in the Java runtime environment then you can use the following code snippet to check.

package org.kodejava.lang;

public class MemoryExample {
    public static void main(String[] args) {
        long freeMemory = Runtime.getRuntime().freeMemory();
        long totalMemory = Runtime.getRuntime().totalMemory();

        System.out.println("Free Memory  = " + freeMemory);
        System.out.println("Total Memory = " + totalMemory);
    }
}

Here is the result of the code snippet above:

Free Memory  = 1018439896
Total Memory = 1029177344

How do I execute other applications from Java?

The following program allows you to run / execute other application from Java using the Runtime.exec() method.

package org.kodejava.lang;

import java.io.IOException;

public class RuntimeExec {
    public static void main(String[] args) {
        //String command = "/Applications/Safari.app/Contents/MacOS/Safari";
        String command = "explorer.exe";

        try {
            Process process = Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}