How Java handles public methods in a thread - java

I'm writing a multithreading application, in my ServerThread.run() method, I use ServerSocket.accept() to receive new incoming connection. Everytime when a new connection arrives, ServerThread creates an other Thread named ClientHandler to handle the connection (Receiving/Sending data), and in my ServerThread, I have a java.util.HashMap<ClientHandler, Socket> to store the references of connected clients and the corresponding sockets.
In my ServerThread, I've implemented a few other public methods, such as shutdown() to stop the server thread, disconnect(int id) to shutdown the connection of a specific client etc. Those methods are usually called by my GUI, from the EDT thread.
I've tested the code, it works, but I'm not sure if it's the best way to do this. I've read lots of Java multithreading tutorials, but they don't add other public methods in their custom java.lang.Thread subclass.
Especially in my ServerThread.run(), I have used the method ServerSocket.accept() which is supposed to be blocking. When I want to shutdown my ServerThread, I have to call ServerSocket.close() to force the thread to stop.
However, when I call for example ServerThread.disconnect(int id) to close the connection of a remote client, it works. Is the ServerThread supposed to be blocking on the accept() method ?
So, my code works, but I don't know why, and I'd like to know if one can add other public methods in a custom subclass of java.lang.Thread ??
Thanks.

The reason you don't add public methods to a Thread class is exactly because this sort of confusion arises - there's an intuition that the Thread class itself 'owns' the execution of those methods, whereas in Java it is -always- the calling thread that owns the execution.
When the EDT thread calls ServerThread.disconnect(id), the code in the disconnect method is being run by the EDT thread, not the ServerThread. The key point here is that the Thread ServerThread, and the Object ServerThread are not quite the same thing, semantically speaking - an Object can't be "blocked" in the same way that a Thread can, the expression doesn't even make sense.

Related

Is it possible to see if a client is trying to connect a ServerSocket?

I have this loop running in a thread:
ServerSocket ss = new ServerSocket(PORT);
while (running) {
ClientHandler ch = new ClientHandler(ss.accept);
}
which keeps a ServerSocket running waiting for a connection. What I want to do is have an if statement that would check if there is a client trying to connect and if not, it will run the while statement again. This would make it easier to stop the thread from running. Currently, I am just having a System.exit(0) in a different part of the code stop the program. So is there a way to only accept a client if there is one waiting to be accepted, otherwise it will test to see if it still needs to run?
Is it possible to see if a client is trying to connect a ServerSocket?
Yes it is possible, though not necessarily advisable.
You need to use a ServerSocketChannel and a Selector. You create the channel and bind it to a port, and then register it with the selector. Then to see if there is an incoming connection, you call selectNow() on the selector to test if the channel is ready.
There is an example at https://www.baeldung.com/java-nio-selector: see section 8.1. (Note that the example uses select() rather than selectNow(). That blocks the thread ... which is not what you want.)
If you really just want a way to stop that listener loop while it is blocked, there are some other alternatives:
Your control thread could just call interrupt() on the Thread that makes the accept() calls. The accept should throw an InterruptedIOException. For completeness, the while should also test the thread's interrupt flag.
I think it is also possible for another thread to call close() on the ServerSocket. If a thread is currently blocked in an accept() call, it should get an exception.
Note: I have not personally tried either of these approaches, so I cannot promise they will work. But either would be a simpler (and probably better) solution than polling using a Selector and selectNow().
Calling System.exit isn't that bad a solution either, IMO.

UDP and Threads - Java

I'm using UDP to communicate through threads, but I want to make some kind of variable to know if the thread waiting for a message has waited too long.
Is there any method inherited by UDP class that I could use?
Or is it a better choice to make my own timekeeper parallel to every thread to keep the time?
Question: If a thread has waited too long for a message, what should it do?
Answer: Stop waiting!
What you should probably do is to call setSoTimeout(int) on the DatagramSocket to set a timeout before you call receive(DatagramPacket). This will cause the thread that is waiting for a message to get a SocketTimeoutException if it waits for longer than the timeout.
To answer your actual question:
There isn't a builtin method that one method can call to see how long another thread has been waiting for a message.
Building a separate timekeeper is possible but rather heavy-weight

Is Jetty websocket client class WebSocketClient thread safe?

Jetty 9.3
Java 8
Is org.eclipse.jetty.websocket.client.WebSocketClient thread safe.
Can multiple threads use a single instance of this class to create a websocket session (with the connect method) ?
It's not, from the code here is at least one example why:
The purpose of WebSocketClient is to provide a mean of establishing connections to remote websocket endpoints.
This is achieved by calling connect() method, which returns Future Session. All right, now imagine that
Thread 1 instantiates a WebSocketClient and calls setCookieStore()
Thread 1 calls connect(Object websocket, URI toUri).
Inside connect() Thread 1 executes
ClientUpgradeRequest request = new ClientUpgradeRequest(toUri)
and
request.setRequestURI(toUri)
Thread 2 executes setCookieStore(CookieStore cookieStore)
Then the request created by Thread 1 may have the cookies corresponding to the URI of Thread 2.
In order to ensure thread safety the internal state of the object should de unmodifiable during the whole connection process.
I can't guarantee that WebSocketClient is 100% thread safe, but I can say that it is meant to be thread safe, to a certain extent.
Looking at the source code, we see that the private method initializeClient is synchronized:
private synchronized void initializeClient() throws IOException
and that the connect method is using an Executor:
// Execute the connection on the executor thread
executor.execute(promise);
The documentation of the class says nothing about thread safety, but the call of the synchronized initializeClient method from the connect method and the use of the Executor are clear signs that some form of multi-threading is supported.
== Edit ==
Thread safety is often guaranteed only for certain types of operations. For examples it can be guaranteed only for read operations and not for write operations. This is the role of the documentation to define the conditions of thread safety. The remark of Sergio Montoro is right, if one thread modify the object during its use by another thread, strange things could happens. In the case of WebSocketClient thread safety is certainly at least restricted to the non-modification of the object by other threads, or to the synchronized and concerted modification of the WebSocketClient internal state.

Java - Run a runnable on an existing thread?

I am trying to switch back to an existing thread from a spawned child interface callback. Does anyone know how? The callback implementation always runs from the child thread where where it was called, not the implementing class...
What do you mean switch back?
Cause a context switch that will return you to "original" thread that spawned the child thread?
If so, this is not possible. It contradicts Multi-threading concepts.
If you want to have some work done on the "original" thread, while the "child" thread is running,
You can consider having a queue between the child and the original thread (i.e - Producer/Consumer).
The child thread will put a "job" on the queue, and the "original" thread will consume it.
However,the "original" thread will have to block on the the "child" thread.
Another way to implement this is using wait and notify, (child thread will notify) - but once again, original thread will have to wait.
Last approach will be to simply wait on the child thread execution to end, if you want to return to the original thread at the end of execution of child thread.
The question is - is waiting at the original thread is acceptable at your scenario?
You simply have the calling thread wait() on an object, and have the child thread notify() the same object.
When wait() is called, the calling thread will halt.
When notify() is called, the waiting thread will wake up and continue on.
These calls must be made within a synchronized block/method.
Swing uses the concept of an Event Dispatch Loop (EDL), and all Swing component interaction must run on the the EDL's thread. This sounds analogous to what you want to do, and to what zaske proposed in his response.
You might find the following helpful in formulating your solution:
SwingUtilities, in particulare it's invokeLater(Runnable) method.
SwingWorker if you want to get fancy and start even more threads.
Since this is also tagged java-ee I'll mention that you are not allowed to start threads in any Java EE app server. It introduces several issues:
Easy to bleed the server of thread resources
Can prevent undeployment of the application
Can prevent server shutdown if threads are not marked as daemons
Loss of functionality such as JNDI, Transactions, Security
It's generally a no-no. You might instead look into the #Asynchronous annotation which allows you to easily do fork/join kinds of logic safely with the cooperation of the container.
This answer has a very complete explanation of how #Asynchronous methods work including example code https://stackoverflow.com/a/6158773/190816

Java Thread to manage socket and run class method

I have a Java thread that I start so it keeps listening to a socket (considering the a socket read is blocking a thread is needed).
After the Thread receives the data from the socket it needs to call a method from a class.
Now I have two options to do this:
Declare an interface that is passed to the Thread and implemented in a class. When the thread calls the interface method the implementing classes will run it.
Or I can pass the class instance to the Thread as a parameter and then call the class method.
But I wanted to know if the thread blocks while the method is running.
I suppose so but I'm not sure.
I wanted the thread to have a Socket event behavior. What I mean is to only be responsible for reading the data from the socket and fire functions in the main Class, the one that called the Thread.
Yes, the thread will block while executing the method, so it can not read from the socket at the same time. No information will be lost, the transfer only takes longer and you can get a socket timeout if the computation takes too long.
If your method takes much time to run, you should execute it in another worker thread. I recommend to use an Executor for that.
You have various options :
Make your class a child class of Thread (easier code but you'll merge functionnal part - your main code - with a technical aspect (extending the Thread))
Make your class implements the Runnable interface and start a new thread with that Runnable (i often do like that). So your main code still remains in a overriden run method, but the inheritance tree is up to you (your main class can extend one of your other class)
Keep separated your main code / the thread with two classes (one for your main code, one for the thread), linking the two at your will (remember that if you make an inner thread inside another class, the inner thread can use any final properties, for example).
As stated in other answers, anything happening in your run() method is of course blocking the execution.
As a sidenote, if you're going to deal with threads and sockets, i strongly suggest you to have a look at NIO frameworks like Netty that are just there for this kind of behavior : event driven client/server application through NewIO sockets.
As another sidenote, i often use this pattern :
start an acquisition thread that will catch the event ;
push them in a linkedblockingqueue (queue.offer()) ;
have another thread that shares the same linkedblockingqueue (with queue.take()) : this operation is blocking, the threads will be blocked as long as the queue is empty ;
This is a very simple way to have one thread as "producer", and one thread as "consumer". You can even have various consumers awaiting on the same queue.
But I wanted to know if the thread blocks while the method is running
Yes it does block.
If inside run you call a method to process something it doesn't matter if that is an interface etc as you ask it only matters what does the method actually do
In your case you have only 1 option.
Make sure that you return the control back to your socket listening thread asap.
This can happen by designing/mandating the processing class to handle the processing in a different thread.
Actually your problem is not something new. In event based designs there is the requirement to process the event as fast as possible so as to not block the event queue based flow.
And this is how I would recommend you to design arround. Not use any interface to interact with the listening thread but register an event listener(s).
When an event occurs i.e. your listening thread reads data, it will pass the data as event to your listener(s) at which point of course it will block.
Then you should start a new thread to do the processing and the listening thread can continue with its work

Categories

Resources