Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7995447
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T14:25:00+00:00 2026-06-04T14:25:00+00:00

I have the following logic (simplified): public class Application { public static volatile boolean

  • 0

I have the following logic (simplified):

public class Application {

    public static volatile boolean stopServer;
    private static ScheduledExecutorService taskScheduler;

    private static Thread listenerThread;

    public static synchronized void switchStopServer() {
        stopServer = true;

        listenerThread.interrupt();
        taskScheduler.shutdownNow();
    }

    public static void main(String[] args) {
            int threadPoolSize = 4;
            taskScheduler = Executors.newScheduledThreadPool(threadPoolSize);

            listenerThread = new ListenerThread();
            taskScheduler.schedule(listenerThread, 0, TimeUnit.NANOSECONDS);
    }

}

public class ListenerThread extends Thread {

    private static ServerSocket serverSocket;
    private Socket socketConnection;

    @Override
    public void run() {
         while (!Application.stopServer) {
              try {
                   socketConnection = serverSocket.accept();
                   new CommunicatorThread(socketConnection).start();
              } catch (SocketException e) {
              } catch (Exception e) {
              }
         }  
    }

    private static void closeServerSocket() {
         try {
              if (serverSocket != null && !serverSocket.isClosed()) serverSocket.close();
         } catch (Exception e) { }
    }

    @Override
    public void interrupt() {
         closeServerSocket();
         super.interrupt();
    }

}

What I want to achieve, is to terminate Threads the proper way. First of all, is this (switchStopServer()) the correct way to do that, or are there any better solutions?

I’m a little confused with the ScheduledExecutorService, because shutdownNow() does not interrupt the Threads, neither does ScheduledFuture.cancel(true) (at least for me it doesn’t), so I can’t interrupt ServerSocket.accept(). I know, in my example there is no need for the ScheduledExecutorService, but in my real application there is.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T14:25:01+00:00Added an answer on June 4, 2026 at 2:25 pm

    Your problem I believe is that you are confusing Thread and Runnable. Even though ListenerThread extends Thread, it is actually not it’s own thread. The thread is managed by the ExecutorService thread-pool which is just calling your run() method. This is only [sort of] working because Thread also implements Runnable. When you call ListenerThread.interrupt() you are not interrupting the thread in the thread-pool although you are calling your interrupt() method but just directly in the calling thread. This should close the socket since it calls closeServerSocket() from the outside.

    When you call ScheduledFuture.cancel(true) or shutdownNow(), the pool thread(s) should be interrupted but this will not call your interrupt() method there. You can test for the interruption by using Thread.currentThread().isInterrupted() in your run() method.

    You should change ListenerThread from extending Thread and instead have it just implement Runnable (see edit below). You will want to do something like the following loop in your run() method:

    while (!Application.stopServer && !Thread.currentThread().isInterrupted()) {
    

    To interrupt the accept() method, you are going to have to close the serverSocket from another thread. Most likely this will be done by the thread that is calling interrupt(). It should close the socket, shutdownNow() or cancel() the thread-pool, and then it can wait for the pool to terminate.

    Edit:

    Actually, I wonder why you are using a pool for your ListenerThread since there will only ever be one of them, it is being scheduled immediately, and it is just starting a new thread on any connection directly. I would remove your taskScheduler pool entirely, keep ListenerThread extending Thread, and just call new ListenerThread().start();.

    The outer thread would still just close the serverSocket to stop the ListenerThread. If you also need to close all of the connections as well then the ListenerThread needs to keep a collection of the socketConnection around so it can call close() on them when the accept() throws a n IOException.

    Also, currently you have private Socket socketConnection; which is misleading because it will change after every call to accept(). I’d rewrite it as:

     Socket socketConnection = serverSocket.accept();
     new CommunicatorThread(socketConnection).start();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have following class public class ButtonChange { private int _buttonState; public void SetButtonState(int
Lets say i have following class public class abc { int id; string name;
I have the following logic: public void InQueueTable(DataTable Table) { int incomingRows = Table.Rows.Count;
I have seen code with the following logic in a few places: public void
Suppose that you have the following logic in place: processMissing(masterKey, masterValue, p.getPropertiesData().get(i).getDuplicates()); public StringBuffer
I need syntax help with the following code logic: I have a code block
I currently have the following in one solution: Core Project (data access, biz logic,
I have the following two interfaces: public interface IMembershipProvider { object Login(ILoginProviderParameters loginParameters); void
I have following method in wcf webenabled service Public Person AddPerson(Person p); As of
I have following requirement, I have C#/.Net console application, which refers to 'System.Data.Sqlite.dll' 'System.Data.Sqlite.dll'

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.