I am trying to get a value from native method in my Java program. But for some reason, the native method is not responding.My program is stuck over there. So, If no response from native method for 2mins, then my java code should have the control again and proceed further.
How should I implement this? Simply I want control back from native method after some time..
you can start a runnable so that thread will call the native method you want , and this will be bugged for 2 mins not the main application.
Runnable updateRunnable = new Runnable() {
#Override
public void run() {
yourObject.yourFuctionCall();
}
}
new Thread(updateRunnable).start();
hope it helps
Related
I'm using POI in a function to fill the content of my excel document (it takes 10 seconds) and when i call my function I want to use a JProgressBar to see the progress, but the button and the program is block, i need to to make in other thread? and how can I do it? an example of my code:
btnEjecutar.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
//the function
generarDocumento(nombre);
}
Try to use an invokeLater, like the example bellow:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generarDocumento(nombre);
});
Event listeners are executed in the UI thread. If an event listener takes a long time, the UI will stop working/lock up/block/hang.
My guess is that the method generarDocumento() takes a long time. If you want the UI to continue working, you must run it in a worker thread. The Java documentation contains several examples how to do that: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
The last example in the tutorial contains demo code how to update a progress bar: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/ProgressBarDemoProject/src/components/ProgressBarDemo.java
Note: The linked content is copyrighted; therefore I can't copy it here.
So I am trying to do a chat type program using JavaFX for the GUI. I have it so a class that acts as a server will loop and keep adding client connections to it.
public void serverconnection()
{
// portnumber was saved from constructor
try (ServerSocket socket = new ServerSocket(this.portnumber))
{
// loop is a bool set to true
while (loop)
{
// this class extends Thread and has its own overwritten start method
new myclass(socket.accept()).start();
}
}
catch (IOException e)
{
System.exit(404);
}
}
so the problem is (I am assuming) was, this loop keeps looping until the program closes. but since I was calling this within the JavaFX's initialize method
public void initialize(URL url, ResourceBundle rb)
{
// constructor, nothing here is needed for this post
myclass z = new myclass(45234);
// problem here, since this has a loop, but
z.serverconnection();
// gui wont load till after this is done
// but serverconnection is only done after program ends
}
the problem with this is, apparently, the GUI will not load until AFTER initialize has finished, but it will not finish until program closes. After google searching, I could not find any fix for this. I need a way to call a method that will do all this, AFTER initialize method has finished. My client side class is similar to this, but the methods to connect on that are activated on events when clicking a login button. For this serverside one, I am trying to start without any interaction with the user. so is there a way to call a method or make this work AFTER initialize method has ran?
You might want to run this loop in a thread, so do something like
Thread t = new Thread(z::serverconnection)
t.start()
If you do this at the end of your initialization() method, it will run exactly then.
This will start a thread which runs forever; you might want to add a feature for interrupting the thread when the program is supposed to be terminated.
Remember that for changing anything in the GUI you need to sumbit a task via Platform.runLater(). This is because the GUI may only be modified from within that one thread. So in order to modify anything, you have to wrap that in a Runnable and submit it for execution.
You can do that in this way:
Platform.runLater(new Runnable() {
#Override
public void run() {
doWhateverNeedsToBeDone();
}
});
In Java 8, you can do anything of the following, depending on the extent of the work to be done:
Platform.runLater(() -> {
doWhateverNeedsToBeDone();
});
Platform.runLater(() -> doWhateverNeedsToBeDone());
Platform.runLater(this::doWhateverNeedsToBeDone);
The latter only works if doWhateverNeedsToBeDone() is a method of this.
I have developed an applet and I am using a JSP to upload it. I have worked it using Netbeans 6.9. The applet works fine without JSP. When I run JSP on Glassfish server, applet does not run.
My applet takes 43 seconds to do processing and get displayed, I think this may be the problem.
When I run the same JSP with the same applet but with slight modification, applet runs correctly with JSP. Modification is that I comment out a function call (called from init() method) which is responsible for large execution time. The long running method reads three files and generates the output in the choice buttons, i.e. generates the choices.
But I need that function in my applet, that is very important function.
Every catch statement has a printstacktrace() method call in it.
public void start(){
initialise_maps();
}
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable()
{
public void run() {
initComponents();
}
});
} catch (Exception ex)
{
ex.printStackTrace();
}
// initialise_maps();
}
Modification is that I comment out a function call (called from init() method) which is responsible for large execution time.
It seems it will be necessary to refactor that method call to the start() method, or do it in a separate Thread (e.g. using a SwingWorker).
The long running method reads three files and generates the output in the choice buttons, i.e. generates the choices.
Add the choice boxes in the init() method, but populate them in the start() method (if not already done - the start method is called every time the browser is restored from minimized, as well as directly after init()).
Every time I do a httpRequest, the screen will appear to be locked up for a few seconds while the code is executing. Hence I used AsyncTask to do all my httpRequest stuff in a separate thread while putting up a ProgressDialog so the user knows something is happening.
I recently encountered the following situation: the input of one of my httpRequest is dependent on the result from a previous httpRequest (+parse) action. I can't just put the two AsyncTasks sequentially cause Android will put them in two threads and start the second one without the first one being finished. And without an appropriate input (the result of the first httpRequest), my second httpRequest will crash the app.
Is there way I can put-in a wait() to force the second AsyncTask not to start until the first one finishes?
I also had some same situation the other day.
I had solved it in this way:
Pass the reference of your activity to the constructor of async class and execute the do in background function. Now in post execute function call a public method of ur activity from async class to execute the task again... or try this:
if (asynclass.getStatus() == android.os.AsyncTask.Status.PENDING) {
asynclass.execute();
} else if (RF.getStatus() == android.os.AsyncTask.Status.FINISHED) {
asynclass = new asyncclass();
asynclass.execute();
} else {
Toast.maketoast(this, "Plz wait", 1).show();
}
Cheers
so i think(not sure),you need to call second asyncTask on post execution method
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
new secTask().execute();
}}
Yes, you can. But it is only possible in onProgressUpdate() or onPostExecute(). Try doing it like this:
private class Task1 extends AsyncTask<Void, Void, Void> {
...
...
protected void onPostExecute(Void unused) {
dialog1.dismiss();
new Task2().execute();
}
}
Similarly, you'll have to put new Task3().execute(); in the onPostExecute() method of Task2's AsyncTask
Don't call them like this in your main code. If you do, then all of them will run together:
// This is wrong
new Task1().execute();
new Task2().execute();
new Task3().execute();
Reference: AsyncTask
How about using executOnExecutor method :
public void runTasks() {
AsyncTask<Void,Void,Void> aTask = myTask();
AsyncTask<Void,Void,Integer> aTask1 = myTask1();
AsyncTask<Void,Void,Void> aTask2 = myTask2();
aTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
aTask1.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
aTask2.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
Stumbled on this thread looking for a better solution than what I currently use, but it still seems the best...
What I do is pass a runnable in the constructor of each of my async tasks.
Either in the post execute or at the end of the do in the background, I launch my next task, if I have one by executing the runnable.
if(doOnPostExec != null)
doOnPostExec.run();
This way I can changeup the order of my asynctasks by the runnables I pass keeping the code flexible, and if I pass no runnable they complete normally. The runnables just contain one line calling the next asynctask.
I just don't like making all those runnables. Was hoping something existed like in vb.net for chaining delegates.
I encountered this problem before. What I did is use a call back interface class and call its method inside the onPostExecute() method. This way you can call another AsyncTask from the callback method.
I have a button in my program that, when pressed, is supposed to take you to my wiki page about the program. I used the following line to do so:
java.awt.Desktop.getDesktop().browse(new java.net.URI("http://supuh.wikia.com/wiki/BHT"));
The problem is that, no matter what environment in which the program is run, I always get the following error:
java.security.AccessControlException: access denied (java.awt.AWTPermission showWindowWithoutWarningBanner)
does anyone know how I can fix this? Note that this only works in the one program. Any other program I make can use the same method with no problem.
Exit hook
At the start of my program, this hook is added. The program runs fine without it...
System.setSecurityManager(new SecurityManager()
{
#Override
public void checkExit(int status)
{
closeFile(status);
}
});
this hook is needed, but the browse(URI uri) method in question won't work with it. Solutions?
This means you are running with a security manager:
SecurityException - if a security manager exists and it denies the AWTPermission("showWindowWithoutWarningBanner") permission, or the calling thread is not allowed to create a subprocess; and not invoked from within an applet or Java Web Started application
If this is an applet, or a Java Web Start app - sign your jar.
Update Adding a security manager to detect program exit is wrong. There are multiple ways to do this properly. In your case I guess this would be most appropriate:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
closeFile();
}
));
Swing-specific solutions are:
if you don't have to perform extra actions, use frame.setDefaultCloseAction(Frame.EXIT_ON_CLOSE)
use addWindowStateListener and check for WindowEvent.WINDOW_CLOSED
That said, two notes:
you must not hold files open for a long time. Use try/catch/finally to open and close them whenever they are needed.
if you really need a security manager at some point, make sure you override the appropriate method of the SecurityManager that checks whether you can open the link. (won't tell you which one, so that you are not tempted to jump onto this solution, which is wrong)
To summarize, I'd go for setDefaultActionOnClose, and close each file right after I finish reading/writing it.
Update 2: After you linked to your original question describing what exactly are you trying to achieve, things change a bit. You are trying to prevent exit, so you do need a SecurityManager. This makes it so that you should override the checkPermission method and do nothing there (i.e. don't throw exceptions), at least when these permissions are checked (they are checked when browse is called):
new AWTPermission("showWindowWithoutWarningBanner")
new FilePermission("<<ALL FILES>>", SecurityConstants.FILE_EXECUTE_ACTION)
Update 3 Here's how exactly to override the method:
#Override
public void checkPermission(Permission permission) {
if (permission instanceof AWTPermission) {
if (permission.getName().equals("showWindowWithoutWarningBanner")) {
return;
}
}
if (permission instanceof FilePermission) {
if (permission.getActions().equalsIgnoreCase("execute")) {
return;
}
}
java.security.AccessController.checkPermission(permission);
}
(you can go without the outer if-s)
Update 4 The above method will work only if you have given permissions to your program. Otherwise it is a not-well documented behaviour of the JVM that overriding security managers are not allowed to be unprivileged. Take a look at this report - the comments say how to work it around.
To make your life simpler, you can simply #Override public void checkPermission(..) with an empty method body.
Instead of using your own SecurityManager, install a shutdown hook instead:
Runnable runnable = new Runnable() {
closeFile(status);
}
Runtime.getRuntime().addShutdownHook(new Thread (runnable, "Close file"));