Item 59: Know and use the libraries

59. Know and use the library

package tryAny.effectiveJava;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.commons.lang3.time.StopWatch;

public class RandomTest {
    public static void main(String[] args) {
        int n = 2 * (Integer.MAX_VALUE / 3);
        int low1 = 0;
        StopWatch sw1 = new StopWatch();
        sw1.start();
        for (int i = 0; i < 1000000; i++) {
            if (random(n) < n / 2) {
                low1++;
            }
        }
        sw1.stop();

        System.out.println(low1); //I don't think it will be around 500,000. 666 666th place.
        System.out.println(sw1.getTime());

        int low2 = 0;
        StopWatch sw2 = new StopWatch();
        sw2.start();
        for (int i = 0; i < 1000000; i++) {
            if (tlr.nextInt(n) < n / 2) {
                low2++;
            }
        }
        sw2.stop();
        System.out.println(low2);//It will be around 500,000.
        System.out.println(sw2.getTime());//The speed does not change much
    }

    static Random rnd = new Random();

    static int random(int n) {
        return Math.abs(rnd.nextInt()) % n;
    }

    static ThreadLocalRandom tlr = ThreadLocalRandom.current();

}

Recommended Posts

Item 59: Know and use the libraries
Item 40: Consistently use the Override annotation
Item 72: Favor the use of standard exceptions
Import the instance and use it on another screen
[Rails] I don't know how to use the model ...
Item 52: Use overloading judiciously
Item 53: Use varargs judiciously
Item 45: Use streams judiciously
Until the use of Spring Data and JPA Part 1
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
Item 83: Use lazy initialization judiciously
Item 26: Don't use raw types
Use swift Filter and Map
About the same and equivalent
Use Docker and Keycloak to specify the access token and execute the API
Item 70: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors