F
F
fife2021-03-06 16:02:23
Java
fife, 2021-03-06 16:02:23

How to create an infinite Java thread without using 100% CPU?

Good afternoon, I wrote a bot, in it I used the creation of three threads that work in endless

while(true){
}

but the fact is that in this way the bot loads the processor by 100%

. I will drop one of the threads here, for example.
This thread, when changing in the log file, pulls out the last line from it. In the program itself, each new line must be processed.
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.file.Paths;


public class LogReader implements Runnable{
    private static String lastLogString = "defaultLast";
    private static String sameMsgInLog = "defaultSame";
    private static long prevLenght = 1;
    private static File logFile = new File(String.valueOf(Paths.get("C:\\logs.txt")));
    @Override
    public void run() {
        while (true){
            if(logChanged()) {
                System.out.println("лог изменен");
                lastLogString = LogReader.readLog(logFile);
            }
        }
    }

    public static String readLog(File logFile){
        String strToReturn = "default";
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(logFile, "r");
            StringBuilder builder = new StringBuilder();
            long length = logFile.length();
            prevLenght = length;
            length--;
            length--;//структура лог файла такова, что после добавления новой строки, за ней следует пустая строка, а эти строки кода переносят указатели на нужную строку
            randomAccessFile.seek(length);
            for (long seek = length; seek >= 0; --seek) {
                randomAccessFile.seek(seek);
                char c = (char) randomAccessFile.read();
                builder.append(c);
                if(c == '\n'){
                    builder = builder.reverse();
                    strToReturn = builder.toString();
                    break;
                }
            }
        } catch (Exception e) {
            System.out.println("Ошибка при чтении файла");
        }
        return strToReturn;
    }

    public static String getLastLogString() {
        if(lastLogString.equals(sameMsgInLog)){
            return "pass";
        }
        sameMsgInLog = lastLogString;
        return lastLogString;
    }

    public static boolean logChanged(){
        if(prevLenght != logFile.length()){
            return true;
        }else{
            return false;
        }
    }
}


I call the getLastLogString method from another thread to get the last line from the log and process it.

Actually the question is, what are other options for solving my problem, which will significantly reduce the load?
Of course, I don’t ask you to write the code for me, but for some inserts / where to google, I will be grateful!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-03-06
@vabka

Instead of asking for information about a file in an endless loop, you need to subscribe to a file change.
Then the OS itself will notify you that the file has changed.
https://docs.oracle.com/javase/7/docs/api/java/nio...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question