UDP and Threads - Java - 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

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.

Java Message passing among threads

Im new to Java and have been stuck on an issue with respect to thread message passing.
What i mean here is- I have 4 threads, one thread reads msg from network and based on type of msg passes on the msg to either parser thread or database thread . Database thread performs some operation and has to send msg back to the first network thread which puts it into socket. Similarly, the parser thread also performs some action and based on result either has to send msg back to network thread or database thread.
Things i have tried-
I have read about notify() wait() for thread communication which does not help in my case as i need one to one msg passing its not braodcast all
I have read about concurrentqueues blockingqueues - Since this is not an ideal producer consumer problem where one thread is producing msgs and other threads reading from it- i cannot use this.
Using this would be like i need to have 5 queues for each communication channel
network->db,
db->network,
parser->network,
parser->db
Is this efficient to go about?
In c++ i was using msging mechanism where i used to just post msg(windows msg) to corresponding thread's msg pool and that thread in its msging pool, would fetch it
Is there any mechanism like message passing in java which i could use?
one thread reads msg from network and based on type of msg passes on the msg to ...database thread. Database thread performs some operation and has to send msg back to the first network thread which puts it into socket.
You're making the "network" thread responsible to wait for messages from the network, and also, to wait for messages from the "database" thread. That's awkward. You may find it somewhere between mildly difficut and impossible to make that happen in a clean, satisfying way.
My personal opinion is that each long-lived thread in a multi-threaded program should wait for only one thing.
What is the reason for having the database thread "send msg back to the first network thread [to be put] into socket?" Why can't the database thread itself put the message into the socket?
If there's a good reason for the database not to send out the message, then why can't "put the message into the socket" be a task that your database thread submits to a thread pool?
I have read about notify() wait() for thread communication which does not help in my case
Would a BlockingQueue help?
I have read about concurrentqueues blockingqueues - Since this is not an ideal producer consumer problem where one thread is producing msgs and other threads reading from it- i cannot use this. Using this would be like i need to have 5 queues for each communication channel.
And? If adding more queues or more threads to a program makes the work that those threads do simpler or makes the explanation of what those queues are for easier to understand, would that be a Bad Thing?
Note about wait() and notify(). Those are low-level methods that are meant to be used in a very specific way to build higher-level mechanisms. I don't know whether the standard Java BlockingQueue implementations actually does use wait() and notify() but it would not be hard to implement a BlockingQueue that actually did use that mechanism. So, if BlockingQueue solves your problem, then that means wait() and notify() solve your problem. You just didn't see the solution.
In fact, I would be willing to bet that wait() and notify() can be used to solve any problem that requires one thread to wait for another. It's just a matter of seeing what else you need to build around them.

How do I interrupt a long running Java Thread in a ThreadPoolExecutor

Here is my situation:
I have a ThreadPoolExecutor on whose Threads I make a HTTP call to a server via SSL. Sometimes, I get a NullPointerException because the client cannot decrypt the server response and the thread just hangs there indefinitely causing a livelock in the pool. Does anybody know a good way to target a specific thread in the pool, check how long it's been running and kill/interrupt it if it's been running for longer than say 3 minutes?
Any suggestions welcome.
If you keep a reference to that thread, then you can call interrupt() method on it in order to interrupt it. for example:
Thread t = new Theard(r);
t.interrupt();
(r is runnable, a job)
With Spring aop you can count the time passed from the moment that start method was triggered.
Another solution is to use your own thread factory, in the factory make sure to interrupt each thread after 3 minutes.
Another approach is to use: ScheduledThreadPoolExecutor
set your task to run for a period of time, and let it end gracefully after one execution.

Java: Closing multiple threads properly

I'm making a simple server that will spawn multiple threads to handle multiple clients. I was wondering the proper way to shut down and close all the various streams and threads when the server is terminated.
I added a shutdownHook that runs a method that tells the server to shutdown. The server, in turn, broadcasts the shutdown call to all of the threads it has opened, which sets a "isClosed" boolean in each thread to true.
What I'm expecting is that each thread, when reaching the end of the run() method and looping up again, hits the while(!isClosed) conditional, thereby properly terminating themselves by closing all the proper sockets/streams and returning.
However, I don't know if this will properly close everything since the program should terminate after the shutdownhook completes. It completes fairly early since all it does is propagate the closing message. Does this mean that some threads won't get enough time to properly close?
If so, would the best method be to have the shutdownhook manually close every thread, ensuring that they have closed, before returning?
You are correct that the threads will likely not have enough time to terminate properly if the server is terminated. However, depending on what you're trying to do, this may or may not be a problem. If there is no cleanup work needed, then you probably do not need to worry about it because having the threads abruptly terminate will cause no issues.
However, if there is cleanup work that needs to be done (such as writing to a database), then you need something else. The best way to do this (in Java) is using an Executor/ExecutorService and related items (http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html). Your problem is addressed well by these, plus you get some nice freebies such as thread pool management so that scaling is much easier. If you spawn a new thread for every client you will have big problems when you try to scale later because you can't be creating a million threads per minute, for example.
Using the Excecutor stuff is a bit of an adjustment if you're used to using raw threads, but it is worth the research. Good luck!
Using an ExecutorService is the modern way of doing it. It takes so much of the fiddly bits away from the code.
Here is a good place to start.
The shutdownHook happens too late in the the cycle to be useful that way. It is expected to complete quickly and the JVM is already on the way down, which could take existing threads with it if they are daemons.
I would just set a read timeout on the connection threads of say 15-30 seconds. If the timeout happens (SocketTimeoutException), close the socket and exit the thread. The clients will have to cope with dropped connections of course, but they have to do that already. Then when you want to shutdown, just stop accepting new connections (e.g. close the ServerSocket and have its accept thread cope correctly with the resulting exception). When all the existing connection threads have exited, the JVM will exit, and that should really take no longer than the timeout period plus the length of the longest transaction. Make sure the connection threads aren't daemons.
If you don't mind clients getting chopped off in mid-transaction, just call System.exit().
Have you considered making your threads daemon threads.
just add t.setdaemon(true); before calling the start method of the thread.
If these threads should be ended when the program is ended than making them daemon will kill them once all the other non daemon thread has ended.
threads that are used in threadpool are good example for threads that should be daemons.
and i really think it can be useful for you.

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