Sign in to follow this  
King Mir

[java] Server with timeout.

Recommended Posts

I'm trying to implement a Server which will timeout after a period of inactivity and stop replying. I have the following code, but it seems to use up my cpu and leaks memmory. Is there a better way to do this?
//various imports

public class LoggingServer extends Thread{
    private static final long IDLE_TIME_MILLIS = 15000;
    private static final int LOGGING_SERVER_PORT = 9091;
    private Collection<TraceLogData> log = Collections.synchronizedCollection(
			new ArrayList<TraceLogData>() );
    private static ServerSocketChannel ssChannel;
    private AtomicBoolean CallCompleate = new AtomicBoolean(false);
    static {
        try {
            ssChannel =;
            ssChannel.socket().bind(new InetSocketAddress(LOGGING_SERVER_PORT));
        } catch (IOException e) {}

    public void run(){
        try {
            long lastConnect = System.currentTimeMillis();
            while( !CallCompleate.get() || System.currentTimeMillis() 
                    < lastConnect + IDLE_TIME_MILLIS ){
                SocketChannel sChannel = ssChannel.accept();
       	            LoggingConnectionHandler handler =
                        new LoggingConnectionHandler(sChannel.socket(), log);
                    lastConnect = System.currentTimeMillis();
                } else {
        } catch (IOException e) {

    public boolean getCallCompleate() {
        return CallCompleate.get();

    public void setCallCompleate(boolean callCompleate) {

Sorry about the mixed tabs and spaces.

Share this post

Link to post
Share on other sites
Do not use Thread.yield(), use Thread.sleep() instead. There you can pass the number of milliseconds you want to wait, e.g. 100ms, or 500ms - depends on how much you want to "load" the server and how fast should be the response.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this