// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package dbcache;

import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.Random;

public class PerfTest {
    private static final int NIT = 5;
    private static final int REP = 10;
    private static final int N = REP * Setup.NREC;
    private static final int NTHREADS = 10;
    private static final Random rng = new Random();
    public static void test (String lbl, DAL dal) throws InterruptedException {
        System.out.println(lbl + ":");
        for(int k = 0; k < NIT; k++) {
            long t1 = System.currentTimeMillis();
            Thread[] t = new Thread[NTHREADS];
            for(int j = 0; j < t.length; j++) {
                t[j] = new Thread(() -> {
                    for(int i = 0; i < N / NTHREADS; i++) {
                        int id = rng.nextInt(Setup.NREC) + 1;
                        try {
                            Big o = dal.getBig(id);
                            if(o.getId() != id) throw new RuntimeException("Ooops");
                        } catch(Exception ex) {
                            System.out.println(ex.getMessage());
                        }
                    }
                });
            }
            for(int j = 0; j < t.length; j++) t[j].start();
            for(int j = 0; j < t.length; j++) t[j].join();
            long t2 = System.currentTimeMillis();
            System.out.printf("%d random record reads in %.1f seconds = %d records per second\n",  N, (t2 - t1) / 1000.0, N * 1000 / (t2 - t1));
        }
        dal.close();
    }
    public static void main(String[] args) throws SQLException, URISyntaxException, ClassNotFoundException, InterruptedException {
        test("Plain JDBC - no app cache", new DAL_JDBC("jdbc:mysql://localhost/test", "root", ""));
        test("Plain JDBC - local app cache", new DAL_LocalCache(new DAL_JDBC("jdbc:mysql://localhost/test", "root", "")));
        test("Plain JDBC - remote app cache", new DAL_RemoteCache(new DAL_JDBC("jdbc:mysql://localhost/test", "root", "")));
        test("JPA - no app cache, no Hibernate level 2 cache", new DAL_JPA("hibernate_mysql_nocache"));
        test("JPA - local app cache, no Hibernate level 2 cache", new DAL_LocalCache(new DAL_JPA("hibernate_mysql_nocache")));
        test("JPA - remote app cache, no Hibernate level 2 cache", new DAL_RemoteCache(new DAL_JPA("hibernate_mysql_nocache")));
        test("JPA - no app cache, local Hibernate level 2 cache", new DAL_JPA("hibernate_mysql_localcache"));
        test("JPA - no app cache, remote Hibernate level 2 cache", new DAL_JPA("hibernate_mysql_remotecache"));
    }
}
