Using the Java Synchronized

Asked

Viewed 107 times

2

I was doing some exercises in Java, and I came across this code below in a question, stating that "The implementation of the method doLog class Escritor must be qualified as synchronized".

How do I qualify the method the way he said? And what kind of modification would I have to make to it to use the synchronized 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();
    }
}

1 answer

3


Just put in the method signature doLog the keyword synchronized, thus:

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

For more information on how synchronized methods work I suggest you see documentation.

  • Blz Gustavo, thanks vlw for the tip.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.