# How can I extract these similar codes into only one method? [closed]

I have implemented three ways of Singleton idiom in Java, and now I want to write some test code to see there performance. Here is my code:

public static void main(String...args) {
long startTime, endTime;
int MAX_ITE = Integer.MAX_VALUE;

// Eagerly initialized static instance guarantees thread safety.
startTime = getCurrentTime();
for(int i = 0; i < MAX_ITE; i++) {
IvoryTower.getInstance();
}
endTime = getCurrentTime();
System.out.println("Hungry initialization time:" + (endTime - startTime));

// Double check locking, thread safe.
startTime = getCurrentTime();
for (int i = 0; i < MAX_ITE; i++) {
}
endTime = getCurrentTime();
System.out.println("Lazy initialization time:" + (endTime - startTime));

// On demand holder
startTime = getCurrentTime();
for (int i =  0; i < MAX_ITE; i++) {
InitializationOnDemandHolder.getInstance();
}
endTime = getCurrentTime();
System.out.println("On demand holder time:" + (endTime - startTime));
}


These blocks of codes are very similar, but since getInstance() is static, I don't know how to extract each block into a same method call. Can anyone help?

## closed as off-topic by forsvarir, Jamal♦Sep 20 '16 at 12:34

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "Questions containing broken code or asking for advice about code not yet written are off-topic, as the code is not ready for review. After the question has been edited to contain working code, we will consider reopening it." – forsvarir, Jamal
If this question can be reworded to fit the rules in the help center, please edit the question.

• Why the hold ? This is a working code using 3 loops but the OP ask for a way to reduce to only 1 loop... – AxelH Sep 20 '16 at 13:08

Simple, with a bit of overhead, calling a run()

    testInstance("IT", () -> IvoryTower.getInstance());
testInstance("IODH", () -> InitializationOnDemandHolder.getInstance());
}

private void testInstance(String title, Runnable r) {
long startTime = getCurrentTime();
for (int i =  0; i < MAX_ITE; i++) {
r.run();
}
long endTime = getCurrentTime();
System.out.println(title + ": " + (endTime - startTime));
}


Possibly with testInstance as lambda too if you do not want a second method.

OR

Runnable[] rs = {
() -> IvoryTower.getInstance(),