I am working on WebMethods Integration Server. Inside there is a java service, which is a static java method for writing data to a log file (server.log) using BufferedWriter and FileWriter. The code of the static method is as follows:
public static void writeLogFile(String message) throws ServiceException{ try { BufferedWriter bw = new BufferedWriter(new FileWriter("./logs/server.log", true)); bw.write(message); bw.newLine(); bw.close(); } catch (Exception e) { throw new ServiceException(e.getMessage()); } }
Note:
- The code has been simplified, for example, for the purpose.
-I cannot change the declaration of the writeLogFile method and attribute. That means it will always be: public static void writeLogFile. This modification is prohibited: public synchronized void writeLogFile.
There is a possibility that the writeLogFile method may be called by different instances, so I need to make sure that there are no two or more instances to access the same resource (server.log) at the same time. This means that if there are two instances trying to access server.log, one of the instances will have to wait for another instance to complete writing data to server.log.
Questions: Should I change the code above? If so, what modification do I need to do? Should I implement โsynchronizedโ inside a static java method?
@EJP:
So which one is the best code to implement synchronization below?
1)
FileWriter fw = new FileWriter("./logs/server.log", true); synchronized (fw) { BufferedWriter bw = new BufferedWriter(fw); bw.write(message); bw.newLine(); bw.close(); }
2)
BufferedWriter bw = new BufferedWriter(new FileWriter("./logs/server.log", true)); synchronized(bw) { bw.write(message); bw.newLine(); bw.close(); }
3)
synchronized(util.class) {
4) Another opinion?
Thanks.
source share