When to use synchronized in Java

后端 未结 2 1679
旧巷少年郎
旧巷少年郎 2020-12-31 12:24

I hope this is going to be enough information, so here it goes. If you need more info, lemme know in the comments.

I have a class that has two inner classes. The inn

2条回答
  •  滥情空心
    2020-12-31 12:50

    Yup, given what you've laid out above, I'd go with:

    private synchronized void outerMethod() {
    ...
    }
    

    Note, this will have the side-effect of blocking one of the callers until the outerMethod() completes. If that is acceptable, cool. If the intent is merely that the code in outerMethod() is run once, and it is OK for the second caller not to be delayed if the first caller is running outerMethod(), you might consider:

    public OuterClass {
        private AtomicBoolean outerMethodHasBeenCalled = new AtomicBoolean();
    
        private void outerMethod() {
            if (outerMethodHasBeenCalled.compareAndSet(false, true)) {
                // do stuff
            }
        }
    ...
    

    See the JavaDoc for AtomicBoolean to grok what is going on there (assuming it is available in Android's Java).

提交回复
热议问题