-1

The code is like below

public class UAUtil {
private static String sUA = null;
private static Object sLock = new Object();
public static void clear() {
    synchronized (sLock) {
        sUA = null;
    }
}
public static String getUserAgent() {
    synchronized (sLock) {
        if (sUA == null) {
            Context context = CoreService.getAppContext();
            sUA = ...;
        }
    }

    return sUA;
}

So I wonder does it matter to return the sUA within or out of the synchronized block?

mianlaoshu
  • 2,342
  • 3
  • 27
  • 48
  • there is so much wrong with this, there is not really enough space to address it all on SO. **Concurrency is easy, Concurrency correctly is extremely hard.** This is actually *to broad* as well as the partial duplicate, and is not complete code so *no MCVE* applies as well. –  Mar 06 '17 at 02:54

2 Answers2

0

No one can tell you a correct answer because the code looks to be incomplete.

That said, given the code you did post why is sUA an instance variable?

Why even keep that as state. A better thing to do if you do not need that state is to return <whatever code is setting sUA>.

If there is code that you do not show that uses that state then pleas show it and ...

Also private static Object sLock = new Object(); is not a proper way to use an object reference to syncrhonize on. It must be declared final to properly guarantee semantics.

A better way would be to make sUA the lock. Instead of using null use the NullObjectPattern and have a value that represents whatever you are using null to mean.

Using a private static final AtomicReference with a value such as "" or some other null value to represent not set, you could use have something to synchronize on and hold the value at the same time. Making for more correct and cleaner code that will be easier to maintain.

Community
  • 1
  • 1
-3

So I wonder does it matter to return the sUA within or out of the synchronized block?

no it does not matter at all, if you return outside of the synchronized block it will be absolutely fine and also if its within the synchronized block the lock will be released correctly so there is no harm.

Here is a good LINK to jon skeet's & Mark Byers answers to a similar question.

Community
  • 1
  • 1
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • @downvoter any thoughts on improving my answer? – Ousmane D. Mar 06 '17 at 02:52
  • this is only partially *correct* given that `sUA` leaks outside the method block and is *"public"* state that is non `final`. It can change before the `return` depending on what `...;` contains. –  Mar 06 '17 at 02:52
  • @JarrodRoberson thanks for the thought. Appreciated. – Ousmane D. Mar 06 '17 at 02:53