I was doing some exercises in Java, and I came across this code below in an issue, stating that "The implementation of the doLog
method of the Escritor
class should be qualified as synchronized
".
How do I qualify the method the way it spoke? And what kind of modification would you have to do in it to use synchronized
of Java?.
public class Escritor extends Thread {
private BufferedReader input;
protected PrintStream out;
Escritor(Socket sock, PrintStream arq) throws IOException {
input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = arq;
}
public void run() {
String line;
try {
while ((line = input.readLine()) != null) {
doLog(line);
}
input.close();
} catch (IOException e) {
}
}
private void doLog(String text) throws IOException {
Date date = new Date();
out.print(date + ":");
out.println(text);
}
}
public class Server {
public static void main(String[] args) throws FileNotFoundException {
Escritor task;
PrintStream out = new PrintStream(new File("log.txt"));
try {
ServerSocket sock = new ServerSocket(8888);
while (true) {
Socket con = sock.accept();
task = new Escritor(con, out);
task.start();
}
} catch (IOException e) {
System.out.println(e);
}
out.close();
}
}