Sign in to follow this  

[java] Server with timeout.

This topic is 3414 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 = ServerSocketChannel.open();
            ssChannel.configureBlocking(false);
            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();
                if(sChannel!=null){
       	            LoggingConnectionHandler handler =
                        new LoggingConnectionHandler(sChannel.socket(), log);
                    handler.start();
                    lastConnect = System.currentTimeMillis();
                } else {
                    Thread.yield();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

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

    public void setCallCompleate(boolean callCompleate) {
        CallCompleate.set(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

This topic is 3414 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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