Does this method need an executable synchronization object?

The following method refers to an object A that implements Runnable. It was called asynchronously by another method from object A and the code inside the run method (therefore, it was called from another thread with a period of 5 seconds).

Can I get exceptions for creating files?

If I make the method synchronized ... the lock is always acquired over object A? The fact that one of the callers calls the run () method confuses me: S

Thanks for your details.

private void saveMap(ConcurrentMap<String, String> map) {
    ObjectOutputStream obj = null;
    try {
        obj = new ObjectOutputStream(new FileOutputStream("map.txt"));
        obj.writeObject(map);

    } catch (IOException ex) {
        Logger.getLogger(MessagesFileManager.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            obj.close();
        } catch (IOException ex) {
            Logger.getLogger(MessagesFileManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    notifyActionListeners();
}
+5
source share
2 answers

Synchronous instance methods use the object thisas a lock and prevent all synchronized instance methods (even others) from running across threads simultaneously.

, , , , .

, saveMap static, - ( ), , , , .

:

, :

private static synchronized void saveMap(Map<String, String> map) {
    ...
}

FYI, static synchronized ( MyClass.class), , .

+6

A run ( 5 ).

, saveMap , , . , .

.

private synchronized void saveMap(ConcurrentMap<String, String> map) { ... }

, . ( ), map.txt .

private void saveMap(ConcurrentMap<String, String> map) {
    File file = ... original code to write to a temporary file ...
    if (file != null) {
        synchronized(this) {
            ... move file over map.txt ...
        }
        notifyActionListeners();
    }
}

, . , map.txt . Java, , , .

0

All Articles