Created
October 19, 2011 11:24
-
-
Save galak-fyyar/1298020 to your computer and use it in GitHub Desktop.
Wrong way to synchronize factory method
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
public class ServiceFactoryImpl_Buggy<T extends Service> { | |
protected Map<String, T> serviceMap = new HashMap<String, T>(); | |
public T getService( String name ) { | |
T result = serviceMap.get( name ); | |
if ( null == result ) { | |
synchronized ( this ) { | |
result = createService( name ); | |
serviceMap.put( name, result ); | |
} | |
} | |
return result; | |
} | |
private T createService( String name ) { | |
... | |
} | |
} |
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
public class ServiceFactoryImpl_Correct<T extends Service> { | |
protected Map<String, T> serviceMap = new HashMap<String, T>(); | |
protected final ReadWriteLock serviceMapLock = new ReentrantReadWriteLock(); | |
public T getService( String name ) { | |
T result; | |
serviceMapLock.readLock().lock(); | |
try { | |
result = serviceMap.get( name ); | |
} finally { | |
serviceMapLock.readLock().unlock(); | |
} | |
if ( result == null ) { | |
serviceMapLock.writeLock().lock(); | |
try { | |
result = serviceMap.get( name ); | |
if (result == null) { | |
result = createService( name ); | |
serviceMap.put( name, result ); | |
} | |
} finally { | |
serviceMapLock.writeLock().unlock(); | |
} | |
} | |
return result; | |
} | |
private T createService( String name ) { | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment