Synchronizing without an object reference

My online course gave me a project, where I have to write to the individual files with their corresponding threads. They also gave me a guideline, which is shown here:

public static void writeToFile(String saveState, String fileName) { 
    //TODO: Write a string to a new file synchronously
}

public static void writeToFileAsync (String saveState, String fileName) {
    //TODO: Write a string to a new file asynchronously
    
    new Thread() {
        public void run(){    
            writeToFile(saveState fileName);
        }
    }.start();
}

I have to make these methods work when I call them by these following statements:

FileManager.writeToFileAsync(ticTacToe.toString(),"ttt.txt");
FileManager.writeToFileAsync(connectFour.toString(),"c4.txt");
FileManager.writeToFileAsync(mastermind.toString(),"mm.txt");

According to this guideline, since both methods aren't synchronized, I used a synchronized block instead.

public class FileManager {
    public static void writeToFile(String saveState, String fileName) {
        synchronized(FileManager.class) {                                  //Locks the class..?
            try(FileWriter fout = new FileWriter(fileName)){
                fout.write(saveState);
            } catch (IOException exc) {
                System.out.println("Error occurred while writing to a file.");
            }
        }
    }
    
    public static void writeToFileAsync(String saveState, String fileName) {
        new Thread() {
            public void run(){
                System.out.println("Writing to a file: " + fileName);

                synchronized(FileManager.class) {      //Also locks the class?      
                    writeToFile(saveState, fileName);
                    System.out.println("Done writing to a file: " + fileName);
                }

            }
        }.start();
    }
} 

I haven't learned about synchronization based on locking a class nor this concept of "new Thread()" statement. (I guess they make a new thread..?) Of course, this code is NOT SYNCHRONIZED AT ALL. Here's one of the outcomes:

Writing to a file: c4.txt
Writing to a file: mm.txt
Writing to a file: ttt.txt
Done writing to a file: c4.txt
Done writing to a file: ttt.txt
Done writing to a file: mm.txt

My desired outcome:

Writing to a file: ttt.txt
Done writing to a file: ttt.txt
Writing to a file: c4.txt
Done writing to a file: c4.txt
Writing to a file: mm.txt
Done writing to a file: mm.txt

So can anybody please tell me about this concept of locking a class and new Thread()?



Read more here: https://stackoverflow.com/questions/67394006/synchronizing-without-an-object-reference

Content Attribution

This content was originally published by Jack at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: