I am pretty new in the whole Servlets area and I am trying to implement a method that will wait for an a time variable given by a user( e.g 1 minute) and then it will start a countdown until the given time reaches 0. I thought the only way I can do that is by using Threads.
I am exporting my Java Project as a war , deploy it but when I import 1 minute the webpage does not prints anything until I reload it and If I go back using my browser the thread is still running.
The code below executes the thread.
Can you please suggest me whether I should use the asychronous threads (and maybe explain a little bit the difference with normal threads) or I can continue using the Thread as it is.
if(minutes<=0) {
out.println("<center><h3>Time cannot be negative</h3></center>");
}
else
{
new Thread(new Runnable(){
public void run() {
try {
out.println("<center><h3>Minutes :"+(minutes)+"</h3></center>");
Thread.sleep(minutes*60000);
out.println("<p align=\"CENTER\"> Return<br>");
} catch (InterruptedException e) {
out.println("Interruption Found");
}
}
}).start();
}
}
You have to answer the HTTP request, without delay. A thread isn't a solution for that.
You may use one of the following:
Using some Ajax (client side controlled)
WebSocket (server side controlled)
Related
I'm writing a program that enables UDP communication between a KUKA robot (programmed in java) and a python server running on a PC. The program on the robot needs to run multiple methods concurrently because it needs to listen/receive messages on 3 sockets simultaneously (they all need to be listening for messages at all times).
I first tried this using multi-threading. My main class is DP_UDP_COMM which start running when the robot is started. When starting some initialization between the robot and python server is done to set up the socket connection, after that the communication processes need to be started. An example of 1 of these 'communication' threads is shown below as Thread UDP_COMM:
//DP_UDP_COMM class is the main class that gets started when the robot starts
public class DP_UDP_COMM extends RoboticsAPITask {
//Some code here
//One of the communication processes that needs to run while the DP_UDP_COMM instance is active
public Thread UDP_COMM = new Thread(new Runnable(){
public void run(){
while(running){
_log.info("Thread Started, Waiting for Action");
try {
ReceiveUDP();
_log.info("Buffer received is: "+String.valueOf(receive));
_log.info("Type received is: "+String.valueOf(ByteProcess.getType(receive)));
if(status==0)
processPacket(receive);
} catch (Exception e) {
// TODO Auto-generated catch block
send = createPacketResponse("ERROR: "+e.getMessage());
try {
SendUDP(send);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace(); }
e.printStackTrace();
}
}
}
});
UDP_COMM.start();
//Some code and other methods here
}
This thread tries to receive a UDP message from a socket using ReceiveUDP(). This is a blocking method so it keeps waiting here untill it receives a message. This message is then processed using processPacket(), which is a method that sends a command to the robot determined by the message that was received. After sending the command it starts listening again for new messages. This loops indefinitely when the robot is active.
The other threads are very similar but use slightly different methods which are bound to different sockets.(For example ReceiveUDPEmergency() which is the same as ReceiveUDP() but with a different socket)
This is working well with one thread, but when running 3 threads concurrently it doesn't work anymore because the threads will wait for each other to complete before looping because ReceiveUDP() is a blocking method.
The solution for this (I think) is to use multi-processing instead of multi-threading because this truly runs them in parallel instead of sequentially.
However when looking at the java.lang.Process documentation I really don't get how creating a process works. In every example they create/start a process from an external .exe file or something like that.
Is it possible to create multiple processes that run multiple methods in parallel within my DP_UDP_COMM instance? How would I do this?
//What have I tried:
As explained above I tried multi-threading at first. But this isn't good enough.
With multi-processing it is not clear how to start a process which just runs a method in parallel to the main instance.
Maybe I'm thinking to complicated, but I have the following situation:
I have a class Server.java extending Thread with the following relevant part of the code:
public void run() {
while(listening) {
try {
ServerThread cst = new ServerThread(serverSocket.accept());
cst.start();
} catch (IOException e) {
listening = false;
System.out.println(e.getMessage());
}
}
}
My ServerThread then handles all the incoming stuff.
My question now is, if there is any possibility to stop this Thread (Server) like for example over the command line.
I tried to add a new class, that would handle command line input and .interrupt() this Thread, but that kinda just made a big mess..
Here's one way:
Provide a setter for listening that can be accessed from another class/thread.
Set a reasonable timeout (say, 1 sec) on the ServerSocket and handle the SocketTimeoutException.
To stop the thread, set listening to false and within 1 second the thread will stop. If you want finer control, investigate the async I/O classes in java.nio.
You can define listening as volatile, with a setter and set that to false from another class whenever you want to stop the Thread.
This question already has an answer here:
How to call asyncTasks periodically
(1 answer)
Closed 8 years ago.
Helly Community. I´m fairly new to Android and probably the biggest noob when it comes to networking and backend.
Right now I´m having following problem.
I´m building a simple chatting application and want my app to check the Parse server for a specific message parseobject.
Getting the Objects, working with them and deleting them works fine.
If i do it only once.
This is how I get messages from the Cloud and add them to my App Layout.
ParseQuery<ParseObject> query = ParseQuery.getQuery("message");
query.whereEqualTo("recipient", getRemote_id());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> messages, ParseException e) {
if(messages != null){
Iterator itr = messages.iterator();
while(itr.hasNext()){
ParseObject message = (ParseObject)itr.next();
addMessageToLayout(message.getString("text"), "in", "new", "");
try {
message.delete();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
I want my app to check for new messages the whole time.
Ive tried with AsyncTask and a while(true) loop. The loop constantly creates new asynctask objects.
As result the app doesn´t react anymore and crashes.
When I use an instance of the runnable class im getting following error: NetworkOnMainThreadException, and the App crashes.
Because of this error i tried using asynctask in the first place. Isn´t a runnably object running on a different thread than the main thread as well?
I tried putting the thread to sleep for some seconds, still the app crashes in case of the async task.
Could the Problem be following: Im using anoher runnable object to update some animation in my app.
I also tried not using any kind of threading as the parse methods already work in background so they probably dont even need one. Again the app crashes because of an NetworkOnMainThreadException.
///_////
The weirdest thing comes now. If i´m not using a loop, and just check for messages when i enter the activity at first i´m getting an NetworkOnMainThreadException, but then the application somehow recovers into the newly opened activity and loads my messages from the server.
During that time of course the UI is blocked though. Still, thats the only way i can get it to work right now.
Doing it with a Handler and the TimerTask works, I can´t seem to close the thread when i exit the Activity though.
Here my code:
public void startLookingForMessages(){
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
new GetMessagesTask().execute();
}
});
}
};
timer.schedule(task, 0, 1000);
}
I found out that im getting the NetworkOnMainThreadException only if i´m trying to shut down the thread or close the while loop when calling onStop(). If I let the thread do its own thing, that means not putting in any code to stop it any time, my app works fine.
How could i overcome this problem?
I know this is getting kinda long. But maybe someone has the same Problem and can get some Info here.
Thanks you for your help already =)
Don't do it this way. Just don't.
Think about it: you're calling an AsyncTask to check periodically if something is there. Now, that gets to be quite expensive. Think about the battery and network resources you waste if that message is not there. Therefore, you waste a lot of resources. It's not a good idea to do it like this. You waste the user's resources. In addition, you also need a service to run in the background, as your app will not always be running.
A good way to solve this is to use Google Cloud Messaging. So what Google Cloud Messaging does is it "pings" a device every time there's an update. This makes life easier on you, as you only need to check if your app has received one of these pings, and it also saves battery and network resources.
If you're using PHP for your server-side application, you can use this to get started with GCM and PHP: GCM with PHP (Google Cloud Messaging)
This page on Google's website should also help with implementing it.
By using GCM, you'll also avoid having infinite loops or checking for more information every x minutes. You don't have to check yourself if new information is available; it'll ping you when it's available.
In my app I got some activities and a ReceiverThread.class.
The Thread is started from two different activities. And everytime I switch to another Activity and recall the former active Activity it starts a new Thread. So if I do some test on my app for about 10 Minutes or the app is simply used for some time, there is a mass of Threads open and all do the same.
Most of the time the Threads are on TimedWait.
This gives me wrong data and causes the app to lag hard, sometimes its not even responding.
Is there a good possibility to stop a thread onPause() or onStop() ? Because many of the methods are deprecated. Or how to resume a previous started Thread and so prevent the Activity from creating a new one?
This is my ReceiverThread.run():
public void run() {
initiateCAN();
while (true) {
try {
Thread.sleep(60);
mHandler.post(r);
} catch (InterruptedException e) {
break;
}
}
}
If something is not clear or missing, please feel free to ask and I will edit my post, but don't just simply downvote.
The recommended way to do this is to use the built-in interrupt system. You can then stop the thread by calling Thread.interrupt() (best in onPause() if you don't want multiple instances). Your run method would need to be somewhat changed:
public void run() {
initiateCAN();
try {
while (!isInterrupted()) {
Thread.sleep(60);
mHandler.post(r);
}
} catch (InterruptedException e) {
}
}
While this might work, it's still better to use a Service or another way to make sure there is only one instance at one time (maybe fragments instead of activities?).
You can use Android Services, and that service starts the thread. When you switch the activity, the services is running and not is necessary start a new thread.
I am having difficulty trying to correctly program my application in the way I want it to behave.
Currently, my application (as a Java Servlet) will query the database for a list of items to process. For every item in the list, it will submit an HTTP Post request. I am trying to create a way where I can stop this processing (and even terminate the HTTP Post request in progress) if the user requests. There can be simultaneous threads that are separately processing different queries. Right now, I will stop processing in all threads.
My current attempt involves implementing the database query and HTTP Post in a Callable class. Then I submit the Callable class via the Executor Service to get a Future object.
However, in order properly to stop the processing, I need to abort the HTTP Post and close the database's Connection, Statement and ResultSet - because the Future.cancel() will not do this for me. How can I do this when I call cancel() on the Future object? Do I have to store a List of Arrays that contains the Future object, HttpPost, Connection, Statement, and ResultSet? This seems overkill - surely there must be a better way?
Here is some code I have right now that only aborts the HttpPost (and not any database objects).
private static final ExecutorService pool = Executors.newFixedThreadPool(10);
public static Future<HttpClient> upload(final String url) {
CallableTask ctask = new CallableTask();
ctask.setFile(largeFile);
ctask.setUrl(url);
Future<HttpClient> f = pool.submit(ctask); //This will create an HttpPost that posts 'largefile' to the 'url'
linklist.add(new tuple<Future<HttpClient>, HttpPost>(f, ctask.getPost())); //storing the objects for when I cancel later
return f;
}
//This method cancels all running Future tasks and aborts any POSTs in progress
public static void cancelAll() {
System.out.println("Checking status...");
for (tuple<Future<HttpClient>, HttpPost> t : linklist) {
Future<HttpClient> f = t.getFuture();
HttpPost post = t.getPost();
if (f.isDone()) {
System.out.println("Task is done!");
} else {
if (f.isCancelled()) {
System.out.println("Task was cancelled!");
} else {
while (!f.isDone()) {
f.cancel(true);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("!Aborting Post!");
try {
post.abort();
} catch (Exception ex) {
System.out.println("Aborted Post, swallowing exception: ");
ex.printStackTrace();
}
}
}
}
}
}
Is there an easier way or a better design? Right now I terminate all processing threads - in the future, I would like to terminate individual threads.
I think keeping a list of all the resources to be closed is not the best approach. In your current code, it seems that the HTTP request is initiated by the CallableTask but the closing is done by somebody else. Closing resources is the responsibility of the one who opened it, in my opinion.
I would let CallableTask to initiate the HTTP request, connect to database and do it's stuff and, when it is finished or aborted, it should close everything it opened. This way you have to keep track only the Future instances representing your currently running tasks.
I think your approach is correct. You would need to handle the rollback yourself when you are canceling the thread
cancel() just calls interrupt() for already executing thread. Have a look here
http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html:
As it says
An interrupt is an indication to a thread that it should stop what it
is doing and do something else. It's up to the programmer to decide
exactly how a thread responds to an interrupt, but it is very common
for the thread to terminate.
Interrupted thread would throw InterruptedException
when a thread is waiting, sleeping, or otherwise paused for a long
time and another thread interrupts it using the interrupt() method in
class Thread.
So you need to explicitly code for scenarios such as you mentioned in executing thread where there is a possible interruption.