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
Related
I have received some code through a school project and I'm failing to understand the purpose of the use of threading in this scenario. The project requires use of a multi threading server to pass. I have the following thread implementation which of a new instance is created every time a new client connects.
The problem is that they are not using the run-method, in my understanding the thread exists when it finishes running the run-method. But even after the thread should have finished running it manages to send further the messages from the propertyStateListener. Why does this work and does this really count as a multi-threaded server?
Starts an instance of the ClientHandler every time a new client connects:
#Override
public void run() {
while (true) {
MessageProducer mp;
try {
Socket socket = serverSocket.accept();
new ClientHandler(socket).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The actual ClientHandler:
private class ClientHandler extends Thread implements PropertyChangeListener {
private Socket socket;
private ObjectInputStream ois;
private ObjectOutputStream oos;
private Message messagerecieved;
public ClientHandler(Socket socket) throws IOException {
this.socket = socket;
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
messageManager.registerListener(this);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
messagerecieved = (Message) evt.getNewValue();
try {
oos.writeObject(messagerecieved);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
}
}
The problem is that they are not using the run-method, in my understanding the thread [exits] when it finishes running the run-method. But even after the thread should have finished running it manages to send further the messages from the propertyStateListener.
You are correct that the code is confusing for sure. They are creating a thread with each instance of ClientHandler but there is no run() method so the thread immediately exits after start() is called. The code would actually still work if ClientHandler did not extend thread.
Why does this work
It is the messageManager thread which is calling back to the ClientHandler.propertyChange(...) method which writes the results back to the socket, not the ClientHandler thread.
does this really count as a multi-threaded server?
There certainly are 2 threads at work here because you have the socket-accept thread and the messageManager thread. Whether or not this is a "multi-threaded server" depends on the assignment I guess. Certainly if there was supposed to be a thread per client then this code does not do that.
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 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.'
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 took this code:
28 public static void main(String[] args) throws IOException {
29 HttpServer httpServer = startServer();
30 System.out.println(String.format("Jersey app started with WADL available at "
31 + "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...",
32 BASE_URI, BASE_URI));
33 System.in.read();
34 httpServer.stop();
35 }
Does line 33 "System.in.read()" means that it will block until there is input? Will this also work when starting the Java application using UNIX rc script - not manually started from a command line?
I'd like to write a Java application to listen for HTTP connections. The application will be started automatically when the system boots (using UNIX rc scripts). It means that the application will run continuously - theoretically forever, until purposefully stopped. What is the best way to implement this in the Java main() method?
It looks like a weird black magic but following does the trick in very elegant way
Thread.currentThread().join();
As a result the current thread, main for instance, waits on join() for thread main, that is itself, to end. Deadlocked.
The blocked thread must not be a daemon thread of course.
Leaving the main method in Java does not automatically end the program.
The JVM exists if no more non-daemon threads are running. By default the only non-daemon thread is the main thread and it ends when you leave the main method, therefore stopping the JVM.
So either don't end the main thread (by not letting the main method return) or create a new non-daemon thread that never returns (at least not until you want the JVM to end).
Since that rule is actually quite sensible there is usually a perfect candidate for such a thread. For a HTTP server, for example that could be the thread that actually accepts connections and hands them off to other threads for further processing. As long as that code is running, the JVM will continue running, even if the main method has long since finished running.
#Joachim's answer is correct.
But if (for some reason) you still want to block the main method indefinitely (without polling), then you can do this:
public static void main(String[] args) {
// Set up ...
try {
Object lock = new Object();
synchronized (lock) {
while (true) {
lock.wait();
}
}
} catch (InterruptedException ex) {
}
// Do something after we were interrupted ...
}
Since the lock object is only visible to this method, nothing can notify it, so the wait() call won't return. However, some other thread could still unblock the main thread ... by interrupting it.
while (true) { ... } should go on for a pretty long time. Of course, you'll have to figure out some way of stopping it eventually.
A common trick is to have some volatile boolean running = true, then have the main loop be while (running) { ... } and define some criteria by which a thread sets running = false.
Back to Threads, thats exactly what i wanted. Btw this awesome tutorial helped me a lot.
Main.java
public class Main {
public static void main(String args[]) {
ChatServer server = null;
/*if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else*/
server = new ChatServer(Integer.parseInt("8084"));
}
}
and ChatServer.java Class extends a Runnable
public class ChatServer implements Runnable
{ private ChatServerThread clients[] = new ChatServerThread[50];
private ServerSocket server = null;
private Thread thread = null;
private int clientCount = 0;
public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start(); }
catch(IOException ioe)
{
System.out.println("Can not bind to port " + port + ": " + ioe.getMessage()); }
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
.... pleas continue with the tutorial
So in the main Method a Runnable is being instantiated and a new Thread as shown in
public void start() {
is being instantiated with the runnable.
That cases the JVM to continue executing the process until you quit the project or the debugger.
Btw thats the same as Joachim Sauer posted in his answere.
Java program terminates when there are no non-daemon threads running. All you need is to have one such running thread. You could do it using infinite loops but that would consume CPU cycles. The following seems like a reasonable way to do it.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {}); //submit a task that does what you want (in this case, nothing)
Also we can achieve the same with the ReentrantLock and call wait() on it:
public class Test{
private static Lock mainThreadLock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
System.out.println("Stop me if you can");
synchronized (mainThreadLock) {
mainThreadLock.wait();
}
}