I actually had a much bigger question, but I reduced it:
How does Socket.connect() behave when close() was called on that Socket before, but no connection attempt was made previously?
Multithreading/Threads is related, because I have one thread that is doing the connecting and one that invokes this and may abort the connection before being connected. Due to the joys of multithreading, an abort could be made before connect() is actually called, even if I synchronized-check with a boolean before. (lets say the abort code gets called just before connect() is doing its work, but after connect() was called - at the beginning of the method for example.)
Some code, heavily reduced:
public class Connecter {
private Socket socket;
public void connect() {
// start the connecting thread, synchronized
}
public void abort() {
// synchronized as well: closes the socket, nulls the refernce, sets a boolean value to true (aborted)
}
private class ConnectingThread extends Thread {
public void run() {
try {
// synchronized: create a socket object and set stuff such as TCP_NODELAY
socket.connect(new InetSocketAddress(ip, port));
// handle stuff afterwards, synced of course
} catch (Exception ex) {
// wow. such exceptions. much handling.
}
}
}
}
How does Socket.connect() behave when close() was called on that Socket before, but no connection attempt was made previously?
It will throw a SocketException with the text 'Socket is closed.'
Related
I seem to have an unusual problem that I can't understand the root cause to.
I am using a ServerSocket to handle connections to a server I'm writing. The ServerSocket accepts connections in it's own thread, and can be controlled from the main thread via isAccepting and isActive variables I set up.
What should happens:
Server starts and is accepting connections (via putty). I use a command to close the server socket. The socket closes and the thread idles (I notice this causes a SocketException that I catch). I use a command to open a new server socket and it accepts connections again. I'm able to connect and can exit the application via a command that shuts down the socket and exits the loop accepting connections
What happens:
Server starts and is accepting connections (via putty). I use a command to close the server socket. The socket closes and the thread idles(I notice this causes a SocketException that I catch). I use a command to open a new server socket and that's where the thread hangs. It does not print out any debug info that's in the code, nor does it responde to opening/closing the ServerSocket. using the Exit command hangs the application on the exit routine. Funny thing is, if I set a breakpoint anywhere in the thread code, it unstucks and completes, exiting.
TL;DR - closing the socket jams the thread until I place a breakpoint, after which the code executes normally.
Tried exporting into an executable JAR and the application hangs on exit, just like in Eclipse.
Relevant parts of code below:
public class ConnectionManager extends Thread implements IEverfreeManager {
private final int defaultPort = 8002;
private boolean isAccepting = true;
private boolean isActive = true;
private static ConnectionManager instance;
private ServerSocket serverSocket;
private int portNumber = defaultPort;
private Socket workSocket;
public static ConnectionManager instance(){
if (instance == null)
instance = new ConnectionManager();
return instance;
}
public ConnectionManager() {
}
public boolean isAccepting() {
return isAccepting;
}
public void setAccepting(boolean isAccepting) {
this.isAccepting = isAccepting;
try{
if (!isAccepting && !serverSocket.isClosed()){
serverSocket.close();
System.out.println("Closed server on port "+portNumber);
} else{
serverSocket = new ServerSocket(portNumber);
System.out.println("Server on port "+portNumber+" is now accepting connections");
}
}catch(Exception e){
System.out.println("failed to stop accepting");
e.printStackTrace();
}
}
public boolean isActive() {
return isActive || isAlive();
}
public void setActive(boolean isActive) {
this.setAccepting(isActive);
this.isActive = isActive;
}
public int getPortNumber() {
return portNumber;
}
public void setPortNumber(int portNumber) {
this.portNumber = portNumber;
}
private int getNewConnectionId(){
return ++connectionIdCounter;
}
#Override
public void run() {
super.run();
try {
System.out.println("Starting up Connection Manager");
System.out.println("Starting server on port "+portNumber);
serverSocket = new ServerSocket(portNumber);
System.out.println("Server running and ready to accept players");
while (isActive){
if (isAccepting){
try{
System.out.println("Waiting for connection...");
workSocket = serverSocket.accept();
System.out.println("Connected with "+workSocket.getInetAddress());
int id = getNewConnectionId();
} catch (SocketException e){
System.out.println("Notice: "+e.getMessage());
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void closeManager() {
setActive(false);
}
Using setAccepting(false) and then setAccepting(true) doesn't produce the
System.out.println("Waiting for connection...");
message until I put a breakpoint in the code.
Using closeManager() after setAccepting(false) produces the same results.
Using just closeManager() without touching setAccepting() exits gracefully (despite having the procedure activated during shutdown)
Any insight would be very appreciated
There's nothing thread-safe in this class. There are very fundamental problems with almost every function.
Both isAccepting and isActive both need to be either volatile or be modified in a synchronized manner to be thread-safe. If another thread is calling functions that mutate these fields and you have your run method already looping over them you may get unpredictable results. Attempting to view boolean flags that have no memory visibility guarantees is always a bad idea.
setAccepting() has a race condition where your run() thread may attempt to listen on a socket that is immediately about to be closed.
The singleton ConnectionMananger instance could have multiples be created. In your case your constructor does nothing but it's generally safer to not have to create instances. Use double checked locking to implement this so only one instance will ever be created.
Your immediate problem could likely be 'fixed' by making both the is* member fields volatile but like I said you still have too many other issues in this class that it would be complete safe to use in a multithreaded environment. In addition, catching Exception and simply printing is usually wrong. And you usually want to subclass runnable and pass that to the thread constructor rather than creating a subclass of thread.
I'm writing a client/server application in Java using sockets. In the server, I have a thread that accepts client connections, this thread runs indefinitely. At some point in my application, I want to stop accepting client connection, so I guess destroying that thread is the only way. Can anybody tell me how to destroy a thread?
Here's my code:
class ClientConnectionThread implements Runnable {
#Override
public void run() {
try {
// Set up a server to listen at port 2901
server = new ServerSocket(2901);
// Keep on running and accept client connections
while(true) {
// Wait for a client to connect
Socket client = server.accept();
addClient(client.getInetAddress().getHostName(), client);
// Start a new client reader thread for that socket
new Thread(new ClientReaderThread(client)).start();
}
} catch (IOException e) {
showError("Could not set up server on port 2901. Application will terminate now.");
System.exit(0);
}
}
}
As you can see, I have an infinite loop while(true) in there, so this thread will never stop unless somehow I stop it.
The right way to do this would be to close the server socket. This will cause the accept() to throw an IOException which you can handle and quit the thread.
I'd add a public void stop() method and make the socket a field in the class.
private ServerSocket serverSocket;
public ClientConnectionThread() {
this.serverSocket = new ServerSocket(2901);
}
...
public void stop() {
serverSocket.close();
}
public void run() {
while(true) {
// this will throw when the socket is closed by the stop() method
Socket client = server.accept();
...
}
}
Generally you don't. You ask it to interrupt whatever it is doing using Thread.interrupt().
A good explanation of why is in the Javadoc.
From the link:
Most uses of stop should be replaced by code that simply modifies some
variable to indicate that the target thread should stop running. The
target thread should check this variable regularly, and return from
its run method in an orderly fashion if the variable indicates that it
is to stop running. (This is the approach that the Java Tutorial has
always recommended.) To ensure prompt communication of the
stop-request, the variable must be volatile (or access to the variable
must be synchronized).
It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either.
For your specific situation you will have to call serverSocket.close, since it does not respond to Thread.interrupt.
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.
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();
I am new to using wait and notify. I have trouble in testing my code. Below is my implementation: (NOTE: I have not included all the implementation)
public class PoolImp {
private Vector<Connection> connections; // For now maximum of 1 connection
public synchronized Connection getconnection() {
if(connections.size == 1() ) {
this.wait();
}
return newConnection(); // also add to connections
}
public synchronized void removeconnection() {
connections.size = 0;
this.notify();
}
}
Below is my test method: conn_1 gets the first connection. conn_2 goes into wait as only maximum of 1 connection is allowed.
I want to test this in such a way that when I call removeconnection, conn_2 gets notified and gets the released connection.
Testing :
#Test
public void testGetConnections() throws SQLException
{
PoolImpl cp = new PoolImpl();
Connection conn_1 = null;
Connection conn_2 = null;
conn_1 = cp.getConnection();
conn_2 = cp.getConnection();
cp.removeConnection(conn_1);}
}
In order to test waiting and notifications, you need multiple threads. Otherwise, the waiting thread will block, and never get to the notifying code, because it is on the same thread.
P.S. Implementing connection pools is not an easy undertaking. I would not even bother, since you can use ready-made ones.
Everyone right, you should take a ready-made class for your connection pool. But if you insist, I've fixed the code for you:
public class PoolImp {
private Vector<Connection> connections; // For now maximum of 1 connection
public synchronized Connection getconnection() {
while(connections.isEmpty()) {
this.wait();
}
return newConnection();
}
public synchronized void removeconnection(Connection c) {
connections.add(c);
this.notify();
}
}
Replacing the if block with a while loop is an improvement but will not solve the real problem here. It will simply force another check on the size of the collection after a notify was issued, to ensure the validity of the claim made while issuing a notify().
As was pointed earlier, you need multiple client threads to simulate this. Your test thread is blocked when you call
conn_2 = cp.getConnection();
Now, it never gets a chance to issue this call as it will wait indefinitely (unless it is interrupted)
cp.removeConnection(conn_1);
I create a class that allows me to open a single instance of my Java program. It uses a daemon thread that open a ServerSocket. if the TCP Port was already taken throws an exception at instantiation time.
The code works normally under linux and windows.
Here is the code i am using:
public class SingleInstaceHandler extends Thread {
private static final Logger log = Logger.getLogger(IEPLC_Tool.class);
private boolean finished = false;
#SuppressWarnings("unused")
private ServerSocket serverSocket;
/*
* Constructor
* Generate the server socket.
* If the TCP door was busy throws IOException.
*/
public SingleInstaceHandler() throws IOException {
#SuppressWarnings("unused")
ServerSocket serverSocket = new ServerSocket(44331);
this.setDaemon(true);
this.start();
log.info("Server socket initialized"); //if commented out it works
}
public void run() {
synchronized (this) {
while (!finished) {
try {
log.debug("Server socket goes to sleep");
this.wait();
log.debug("Server socket waken up");
} catch (InterruptedException e) {
log.debug("ERROR while sending SocketThread2 in wait status");
e.printStackTrace();
System.exit(-1);
}
log.info("Server socket end");
}
}
}
public synchronized void shutdown() {
log.debug("SingleInstaceHandler shutdown() caled");
finished = true;
notifyAll();
}
}
Sometimes instead the port is not kept busy... any idea?
UPPENDED AFTER FURTHER TESTS:
running many other tests. it seams that if the port is taken by something like another SW instance new ServerSocket(44331); throws an exception but sometimes even if the port is not taken for some reason it can not get this resource. in this case no exception is launched and i can open as many instance as i want of my application. maybe i should do some other operation to force the thread to lock the port...
any idea?
Thanks,
Ste
As you are not keeping a reference to the ServerSocket it will be eligible for GC. If you are using the Oracle JDK the socket will be closed when it is GCed (java.net.PlainSocketImpl).
I do feel a bit stupid in posting an answer to my question... well.. my code has a bug that took me long to figure out:
the problem is that in te constructor i do:
ServerSocket serverSocket = new ServerSocket(44331);
instead of:
this.serverSocket = new ServerSocket(44331);
I did not notice it before... basicaly the bug was that I was declaring a local socket within the constructor. When the constructur procedure was terminated the socket was released or not depending on the Garbadge Collector. Behavior was quite random. Funny part was that plenty of time calling/not calling the logger was enougth to make the Garbadge collector starting or not. It took me quite a while in noticing the mistake.
furthermore it's better to put a :
this.serverSocket.close() after the wait.
Thans for helping anyway!
Cheers,
Ste