I need to create a Java method to return true
or false
randomly. How can I do this?
Java's Random
class makes use of the CPU's internal clock (as far as I know). Similarly, one can use RAM information as a source of randomness. Just open Windows Task Manager, the Performance tab, and take a look at Physical Memory - Available: it changes continuously; most of the time, the value updates about every second, only in rare cases the value remains constant for a few seconds. Other values that change even more often are System Handles and Threads, but I did not find the cmd
command to get their value. So in this example I will use the Available Physical Memory as a source of randomness.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public String getAvailablePhysicalMemoryAsString() throws IOException
{
Process p = Runtime.getRuntime().exec("cmd /C systeminfo | find \"Available Physical Memory\"");
BufferedReader in =
new BufferedReader(new InputStreamReader(p.getInputStream()));
return in.readLine();
}
public int getAvailablePhysicalMemoryValue() throws IOException
{
String text = getAvailablePhysicalMemoryAsString();
int begin = text.indexOf(":")+1;
int end = text.lastIndexOf("MB");
String value = text.substring(begin, end).trim();
int intValue = Integer.parseInt(value);
System.out.println("available physical memory in MB = "+intValue);
return intValue;
}
public boolean getRandomBoolean() throws IOException
{
int randomInt = getAvailablePhysicalMemoryValue();
return (randomInt%2==1);
}
public static void main(String args[]) throws IOException
{
Main m = new Main();
while(true)
{
System.out.println(m.getRandomBoolean());
}
}
}
As you can see, the core part is running the cmd systeminfo
command, with Runtime.getRuntime().exec()
.
For the sake of brevity, I have omitted try-catch statements. I ran this program several times and no error occured - there is always an 'Available Physical Memory' line in the output of the cmd command.
Possible drawbacks:
main()
function , inside the while(true)
loop, there is no Thread.sleep()
and still, output is printed to console only about once a second or so.