In a case where you are working with a multi-threaded application where multiple threads need to write to a single log file, how would you ensure that the writes to the file are thread-safe and that the data is not corrupted?
- a. Use a single FileWriter instance shared among threads.
- b. Implement synchronization using synchronized blocks or methods.
- c. Create a separate log file for each thread.
- d. Use a ThreadLocal variable for each thread's log writer.
To ensure thread-safety when multiple threads write to a single log file, you should implement synchronization using synchronized blocks or methods. This prevents concurrent writes from interfering with each other. Using a shared FileWriter instance (Option a) without synchronization may lead to data corruption. The other options do not provide effective thread-safety.
Loading...
Related Quiz
- What issues might arise if methods modifying static variables are not synchronized?
- What will happen if the DriverManager is unable to connect to the database using the provided URL?
- Which of the following methods returns the number of rows affected by the DML operation?
- The expression a != b returns true if a is ______ b.
- If we have a 2D array int[][] arr, the expression arr[i] refers to the __________.