Even if in 1 line
public static void blockHost(String hostName) {
blockedHosts.get().put(hostName, hostName);
}
effectively consists of 2 operations, so if you want your methods to be atomic you still need synchronization. You could have an interleaving like:
T1 invokes blockHost("123")
and executes get()
T2 invokes isHostBlocked("123")
, does executes get()
and containsKey()
and returns false
T1 does put(hostName, hostName);
the result of T1 is wrong because blockHost
was invoked before.
I think that you need synchronization, and if you do you can probably avoid using AtomicReference
Off topic - I don't like static things... see this question on SO this question on SO
Even if in 1 line
public static void blockHost(String hostName) {
blockedHosts.get().put(hostName, hostName);
}
effectively consists of 2 operations, so if you want your methods to be atomic you still need synchronization. You could have an interleaving like:
T1 invokes blockHost("123")
and executes get()
T2 invokes isHostBlocked("123")
, does executes get()
and containsKey()
and returns false
T1 does put(hostName, hostName);
the result of T1 is wrong because blockHost
was invoked before.
I think that you need synchronization, and if you do you can probably avoid using AtomicReference
Off topic - I don't like static things... see this question on SO
Even if in 1 line
public static void blockHost(String hostName) {
blockedHosts.get().put(hostName, hostName);
}
effectively consists of 2 operations, so if you want your methods to be atomic you still need synchronization. You could have an interleaving like:
T1 invokes blockHost("123")
and executes get()
T2 invokes isHostBlocked("123")
, does executes get()
and containsKey()
and returns false
T1 does put(hostName, hostName);
the result of T1 is wrong because blockHost
was invoked before.
I think that you need synchronization, and if you do you can probably avoid using AtomicReference
Off topic - I don't like static things... see this question on SO
Even if in 1 line
public static void blockHost(String hostName) {
blockedHosts.get().put(hostName, hostName);
}
effectively consists of 2 operations, so if you want your methods to be atomic you still need synchronization. You could have an interleaving like:
T1 invokes blockHost("123")
and executes get()
T2 invokes isHostBlocked("123")
, does executes get()
and containsKey()
and returns false
T1 does put(hostName, hostName);
the result of T1 is wrong because blockHost
was invoked before.
I think that you need synchronization, and if you do you can probably avoid using AtomicReference
Off topic - I don't like static things... see this question on SO