Last active
July 8, 2017 20:58
-
-
Save akhawaja/52ef0278aa8a1bd443808330b76bfb71 to your computer and use it in GitHub Desktop.
Utility methods for the Java programming language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.amirkhawaja; | |
import java.security.SecureRandom; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
public class Utilities() { | |
private static final SecureRandom random; | |
static { | |
random = new SecureRandom(); | |
} | |
/** | |
* Private constructor. | |
*/ | |
private Utilities() { | |
} | |
/** | |
* Create a new Thread Pool that will not chew max out CPU utilization. | |
* | |
* @return New thread pool. | |
*/ | |
public static ExecutorService newThreadPool() { | |
final int processors = Runtime.getRuntime().availableProcessors(); | |
final int utilization = 1; | |
final int waitComputeRatio = 50; | |
// Number of threads: Number of CPU * CPU utilization * (1 + W/C) | |
final int nThreads = processors * utilization * (1 + waitComputeRatio); | |
return Executors.newFixedThreadPool(nThreads, runnable -> { | |
final Thread thread = new Thread(runnable); | |
thread.setDaemon(true); | |
return thread; | |
}); | |
} | |
/** | |
* Generate a random alphanumeric string. | |
* | |
* @return Random alphanumeric string. | |
*/ | |
public static String randomAlphanumeric(int length) { | |
if (length == 0) { | |
return ""; | |
} else if (length < 0) { | |
throw new IllegalArgumentException("Length must be greater than zero"); | |
} | |
final StringBuilder buffer = new StringBuilder(length); | |
char ch; | |
final int start = ' '; | |
final int end = 'z' + 1; | |
final int gap = end - start; | |
while (length-- != 0) { | |
ch = (char) (random.nextInt(gap) + start); | |
if (Character.isLetterOrDigit(ch)) { | |
buffer.append(ch); | |
} else { | |
length++; | |
} | |
} | |
return buffer.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment