Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this method in runnable object needs synchronization?

The following method belongs to an object A that implements Runnable. It's called asynchronously by other method from the object A and by code inside the run method (so, it's called from other thread, with a period of 5 seconds).

Could I end up with file creation exceptions?

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

Thanks for your inputs.

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();
}
like image 288
HInterface Avatar asked May 12 '12 23:05

HInterface


1 Answers

Synchronized instance methods use the this object as the lock and prevent simultaneous execution of all synchronized instance methods (even other ones) from different threads.

To answer your question regarding requirements for synchronization, the answer is basically yes because you have multiple threads accessing the same method, so output may collide.

As a design comment, I would make your saveMap method static, because it doesn't access any fields (it's stateless), and it more strongly indicates that output to the file is not dependent on the instance, so it's more obvious that file output may collide with other instances.

Edited:

Here's the code for what I'm suggesting:

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

FYI, static synchronized methods use the class object (ie MyClass.class), which is a singleton, as the lock object.

like image 149
Bohemian Avatar answered Sep 29 '22 12:09

Bohemian