I am writing a console application in Java. It is similar to a chat client: Input and output are asynchronously made. The problem is that if some output is made while the user is in the middle of typing, the lines will get mixed up on the screen.

I am looking for a solution which allows me to have a input area separate from the output area. At the moment I am using an extra thread which polls a BufferedReader on System.in. 

The program needs to run on a Linux server and be accessed via an ssh session. So any hints that only work in this environment are fine.

Are there any high level libraries which can do this? Or is there a smart trick using terminal / ANSI codes? The ANSI codes s (save cursor) and r (restore cursor) might be helpful but how do i know where to jump to do the output and how do i handle scrolling?