Using Java synchronized

2

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();
    }
}
    
asked by anonymous 06.10.2017 / 21:32

1 answer

3

Just put the doLog keyword in the signature of method synchronized , like this:

private synchronized void doLog(String text) {
    //seu código sincronizado;
}

For more information on how synchronized methods work, I suggest that you look at documentation .

    
06.10.2017 / 21:42