smali

вторник, 16 сентября 2014 г.

Double-checked locking

Multiton - registry of singletons

Multiton - registry of singletons
http://en.wikipedia.org/wiki/Multiton_pattern

<<

import java.util.HashMap;
import java.util.Map;
public class FooMultiton {
private static final Map<Object, FooMultiton> instances = new HashMap<Object, FooMultiton>();
private FooMultiton() {
// no explicit implementation
}
public static synchronized FooMultiton getInstance(Object key) {
// Our "per key" singleton
FooMultiton instance = instances.get(key);
if (instance == null) {
// Lazily create instance
instance = new FooMultiton();
// Add it to map
instances.put(key, instance);
}
return instance;
}
// other fields and methods ...
}
>>

Singleton pattern with combination of lazy loading and thread safety



Singleton pattern with combination of lazy loading and thread safety
http://stackoverflow.com/questions/15792186/singleton-pattern-with-combination-of-lazy-loading-and-thread-safety


<<

import junit.framework.*;
final class LazySingleton {
private int i;
private static class LazySingletonLoader {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private LazySingleton() {
if (LazySingletonLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static LazySingleton getReference() {
return LazySingletonLoader.INSTANCE;
}
public int getValue() { return i; }
public void setValue(int x) { i = x; }
}
public class LazySingletonPattern extends TestCase {
public void test() {
LazySingleton s = LazySingleton.getReference();
String result = "" + s.getValue();
System.out.println(result);
assertEquals(result, "0");
LazySingleton s2 = LazySingleton.getReference();
s2.setValue(9);
result = "" + s.getValue();
System.out.println(result);
assertEquals(result, "9");
try {
// Can't do this: compile-time error.
// LazySingleton s3 = (LazySingleton)s2.clone();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(LazySingletonPattern.class);
}
}
>>