Created
November 9, 2014 05:52
-
-
Save sheimi/aab9b9627471f5f05936 to your computer and use it in GitHub Desktop.
code in blog.sheimi.me: 2012-06-20-software-architecture-review-5 (1)
This file contains hidden or 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
import java.util.*; | |
public class Limiton { | |
private static int limit = 3; | |
private static Limiton[] instances = new Limiton[3]; | |
private static Random r = new Random(); | |
static { | |
for (int i = 0; i < limit; i++) { | |
instances[i] = new Limiton(); | |
} | |
} | |
private Limiton(){} | |
public static Limiton getInstance() { | |
int i = r.nextInt(limit); | |
return instances[i]; | |
} | |
} | |
// Thread safe version | |
import java.util.*; | |
public class Limiton { | |
private static int limit = 3; | |
private static class LimitonHolder { | |
private static Limiton[] instances = new Limiton[3]; | |
static { | |
for (int i = 0; i < limit; i++) { | |
instances[i] = new Limiton(); | |
} | |
} | |
} | |
private static Random r = new Random(); | |
private Limiton(){} | |
public static Limiton getInstance() { | |
int i = r.nextInt(limit); | |
return LimitonHolder.instances[i]; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment