简体   繁体   中英

Synchronizing on an object, clarification needed

If the goal here is to make sure that while List is being serialized and written to file, no changes are made to the it, what method does a better job?

private void save() throws IOException {
    FileUtils.deleteQuietly(f);
    synchronized (list_of_important_data) {
        FileManipulationUtils.writeObject(list_of_important_stuff, MY_FILE);
    }
}

private void synchronized save() throws IOException {
    FileUtils.deleteQuietly(f);
    FileManipulationUtils.writeObject(list_of_important_stuff, MY_FILE);
}

Do they both do the same thing for the purposes described? Is one better then the other?

They don't do the same thing at all.

The first synchronizes on the list; the second on the object you called save() on. As they synchronize on different objects, they defend against different concurrency races.

The first protects against mutation of the list while it is being saved, provided all mutation functions/accesses are likewise synchronized.

The second protects against save() being executed concurrently with itself, or (more importantly) any other method synchronized on the saved object.

Asking which is better than the other isn't sensible. They don't even remotely do the same thing, and therefore are not remotely comparable. Which one is best is going to depend on exactly what you are trying to achieve by synchronizing in the first place.

Given the confusion in your question, I suspect the answer might well be 'none-of-the-above', and in fact you need to rethink your concurrency design. To help with that, we will need to see more of your code, and have a better idea of what you are trying to achieve.

    private void synchronized save() throws IOException {
        FileUtils.deleteQuietly(f);
        FileManipulationUtils.writeObject(list_of_important_stuff, MY_FILE);
    }

is same as

    private void save() throws IOException {
        synchronized(this){
            FileUtils.deleteQuietly(f);
            FileManipulationUtils.writeObject(list_of_important_stuff, MY_FILE);
        }
    }

choose a lock-shorter one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM