NetBeans' HintsController and EventQueue - java

We are building an application based on the Netbeans Platform, and one part of it is an editor for a specific language we use.
We have the following class to highlight errors in the syntax:
class SyntaxErrorsHighlightingTask extends org.netbeans.modules.parsing.spi.ParserResultTask {
public SyntaxErrorsHighlightingTask () {
}
#Override
public void run (org.netbeans.modules.parsing.spi.Parser.Result result, org.netbeans.modules.parsing.spi.SchedulerEvent event) {
try {
final javax.swing.text.Document document = result.getSnapshot().getSource ().getDocument(false);
final List<ErrorDescription> errors = new ArrayList<ErrorDescription> ();
// finds errors on the document and add them to 'errors' list
}
/***
OFFENDING CODE GOES HERE
***/
} catch (javax.swing.text.BadLocationException ex1) {
org.openide.util.Exceptions.printStackTrace (ex1);
} catch (org.netbeans.modules.parsing.spi.ParseException ex1) {
Exceptions.printStackTrace (ex1);
}
}
#Override
public int getPriority () {
return 100;
}
#Override
public Class<? extends Scheduler> getSchedulerClass () {
return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER;
}
#Override
public void cancel () {
}
}
The offending code, that throws an exception, is this:
org.netbeans.spi.editor.hints.HintsController.setErrors (document, "testsequence", errors);
Based on searching results, it was changed to the following:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
System.err.println("is EDT? " + SwingUtilities.isEventDispatchThread());
HintsController.setErrors (document, "testsequence", errors);
}
});
The following is what happens when a syntax error is introduced in the editor:
is EDT? true
SEVERE [org.openide.util.RequestProcessor]: Error in RequestProcessor org.netbeans.spi.editor.hints.HintsController$1
java.lang.IllegalStateException: Must be run in EQ
at org.netbeans.editor.Annotations.addAnnotation(Annotations.java:195)
at org.netbeans.modules.editor.NbEditorDocument.addAnnotation(NbEditorDocument.java:251)
at org.openide.text.NbDocument.addAnnotation(NbDocument.java:504)
at org.netbeans.modules.editor.hints.AnnotationHolder$NbDocumentAttacher.attachAnnotation(AnnotationHolder.java:235)
at org.netbeans.modules.editor.hints.AnnotationHolder.attachAnnotation(AnnotationHolder.java:208)
at org.netbeans.modules.editor.hints.AnnotationHolder.updateAnnotationOnLine(AnnotationHolder.java:674)
at org.netbeans.modules.editor.hints.AnnotationHolder.setErrorDescriptionsImpl(AnnotationHolder.java:899)
at org.netbeans.modules.editor.hints.AnnotationHolder.access$1300(AnnotationHolder.java:113)
at org.netbeans.modules.editor.hints.AnnotationHolder$4.run(AnnotationHolder.java:812)
at org.netbeans.editor.BaseDocument.render(BaseDocument.java:1409)
at org.netbeans.modules.editor.hints.AnnotationHolder.setErrorDescriptions(AnnotationHolder.java:809)
at org.netbeans.modules.editor.hints.HintsControllerImpl.setErrorsImpl(HintsControllerImpl.java:111)
at org.netbeans.modules.editor.hints.HintsControllerImpl.setErrors(HintsControllerImpl.java:93)
at org.netbeans.spi.editor.hints.HintsController$1.run(HintsController.java:79)
at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1424)
at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:1968)
Caused: org.openide.util.RequestProcessor$SlowItem: task failed due to
at org.openide.util.RequestProcessor.post(RequestProcessor.java:425)
at org.netbeans.spi.editor.hints.HintsController.setErrors(HintsController.java:77)
at com.#.#.#.editor.parser.SyntaxErrorsHighlightingTask$1.run(SyntaxErrorsHighlightingTask.java:74)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:148)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
[catch] at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
What happens is, the call is to HintsController is being made in the EDT (EventDispatch Thread). However, Annotations.addAnnotation() is being run in another thread - sometimes in the "System clipboard synchronizer" thread, sometimes in the "Inactive RequestProcessor" thread. Since it checks if its being run on the EDT, it always throws an IllegalStateException.
I'm no expert in using the Netbeans Platform, and I'm pretty new to this specific application on the company - so I might be missing something really obvious. Google didn't help much. Anyone has any advice?

Turns out, it was not a problem with the code after all.
As pointed on the NetBeans-dev list:
HintsController.setErrors can be called from any thread - it uses its
own worker thread, and reschedules to AWT thread when necessary.
The requirement to invoke Annotations.addAnnotation in AWT thread has
been removed quite some time ago by:
http://hg.netbeans.org/main-silver/rev/db82e4e0fbcc
The same changeset also removed automatic rescheduling into AWT thread
in NbDocument.addAnnotation. So it seems that the build you are using
has the second part of the changeset, but not the first part (...)
After a careful review of maven's pom.xml files, I realized that the application was loading newer versions of the libs while the module was loading older versions, so it would run the wrong code. Related SO question about that here.

Maybe you should try to update your errors with a method like this one :
private void updateError(javax.swing.text.Document document, List<ErrorDescription> errors) {
if(javax.swing.SwingUtilities.isEventDispatchThread()) {
HintsController.setErrors (document, "testsequence", errors);
}
else {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
HintsController.setErrors (document, "testsequence", errors);
}
});
}
}

Related

can't get sequential behavior Java Swing [duplicate]

basically, I have this code which was initially working with console i/o now I have to connect it to UI. It may be completely wrong, I've tried multiple things although it still ends up with freezing the GUI.
I've tried to redirect console I/O to GUI scrollpane, but the GUI freezes anyway. Probably it has to do something with threads, but I have limited knowledge on it so I need the deeper explanation how to implement it in this current situation.
This is the button on GUI class containing the method that needs to change this GUI.
public class GUI {
...
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.startTest(index, idUser);
}
});
}
This is the method startTest from another class which contains instance of Question class.
public int startTest() {
for (int i = 0; i < this.numberofQuestions; i++) {
Question qt = this.q[i];
qt.askQuestion(); <--- This needs to change Label in GUI
if(!qt.userAnswer()) <--- This needs to get string from TextField
decreaseScore(1);
}
return actScore();
}
askQuestion method:
public void askQuestion() {
System.out.println(getQuestion());
/* I've tried to change staticaly declared frame in GUI from there */
}
userAnswer method:
public boolean userAnswer() {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
if( Objects.equals(getAnswer(),userInput) ) {
System.out.println("Correct");
return true;
}
System.out.println("False");
return false;
}
Thanks for help.
You're correct in thinking that it related to threads.
When you try executing code that will take a long time to process (eg. downloading a large file) in the swing thread, the swing thread will pause to complete execution and cause the GUI to freeze. This is solved by executing the long running code in a separate thread.
As Sergiy Medvynskyy pointed out in his comment, you need to implement the long running code in the SwingWorker class.
A good way to implement it would be this:
public class TestWorker extends SwingWorker<Integer, String> {
#Override
protected Integer doInBackground() throws Exception {
//This is where you execute the long running
//code
controller.startTest(index, idUser);
publish("Finish");
}
#Override
protected void process(List<String> chunks) {
//Called when the task has finished executing.
//This is where you can update your GUI when
//the task is complete or when you want to
//notify the user of a change.
}
}
Use TestWorker.execute() to start the worker.
This website provides a good example on how to use
the SwingWorker class.
As other answers pointed out, doing heavy work on the GUI thread will freeze the GUI. You can use a SwingWorker for that, but in many cases a simple Thread does the job:
Thread t = new Thread(){
#Override
public void run(){
// do stuff
}
};
t.start();
Or if you use Java 8+:
Thread t = new Thread(() -> {
// do stuff
});
t.start();

NullPointerException while fast updating TextField

I'm working on an app, that searches some files in the directed folder and prints them in TableView<myFile> foundFilesList, that is stored in the Main class. myFile just extends File a bit. The searching is done using service in background thread, that puts found data to ObservableList<myFile> filesOfUser.
I want to display current amount of find files in TextField foundFilesAmount in the same view, where TableView with files is located -- ResultsView
To do that, I added a ListChangeListener for foundFilesList to ResultsView controller, that uses method setText to print current size of filesOfUser. It looks like:
Main.filesOfUser.addListener(new ListChangeListener<myFile>() {
#Override
public void onChanged(Change<? extends myFile> c) {
while (c.next()){
if (c.wasAdded())
setCounter(c.getAddedSize());
}
}
});
void setCounter (int number) contains only
int currValue = Integer.valueOf(foundFilesAmount.getText());
foundFilesAmount.setText(String.valueOf(currValue + number));
And now what the problem is. Textfield with current amount of find files is updated very fast, and from one moment it stops doing it. In the console I see lots of repeated NullPointerException's from JavaFX Application Thread. Its' contents:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at com.sun.javafx.text.PrismTextLayout.getRuns(PrismTextLayout.java:236)
at javafx.scene.text.Text.getRuns(Text.java:317)
at javafx.scene.text.Text.updatePGText(Text.java:1465)
at javafx.scene.text.Text.impl_updatePeer(Text.java:1500)
at javafx.scene.Node.impl_syncPeer(Node.java:503)
at javafx.scene.Scene$ScenePulseListener.synchronizeSceneNodes(Scene.java:2290)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2419)
at com.sun.javafx.tk.Toolkit.lambda$runPulse$30(Toolkit.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:354)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:381)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:510)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:490)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$404(QuantumToolkit.java:319)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
I tried to set sort of delay before using setText, like updating value in foundFilesAmount only after 5'th, 10'th, 15'th update, etc. But if the search works longer, exceptions are still thrown.
Is there a correct method to show current amount of found files, that contains real amount and doesn't cause so much exceptions?
Thanks in advance.
The correct way is not doing the updates of the UI on a thread other than the application thread. This can otherwise lead to issues with rendering/layouting.
You could use a Task to do the updates to the updates however:
Task<ObservableList<myFile>> task = new Task<
Task<ObservableList<myFile>>() {
#Override
protected ObservableList<myFile> call() throws Exception {
ObservableList<myFile> files = FXCollections.observableArrayList();
while (...) {
...
files.add(...);
updateMessage(Integer.toString(files.size()));
...
}
return files;
}
};
task.setOnSucceeded(evt -> tableView.setItems(task.getValue()));
Thread t = new Thread(task);
textField.textProperty().bind(task.messageProperty());
t.setDaemon(true);
t.start();
try something like this:
Platform.runLater(new Runnable() {
#Override
public void run() {
// update your JavaFX controls here
}
});

Wait for thread to finish in Java

I have some code which executes a download in a separate thread, created so that the JFrame GUI will continue to update during the download. But, the purpose is completely defeated when I use Thread.join(), as it causes the GUI to stop updating. I need a way to wait for the thread to finish and still update the GUI.
You can have the task that does the download also fire an event to the GUI.
For example:
Runnable task = new Runnable() {
public void run() {
// do your download
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// call some method to tell the GUI that the download finished.
}
});
}
};
and then to run it, either use an Executor (preferred method) or a raw thread:
executor.execute(task);
or
new Thread(task).start();
As pointed out in the comments, you'd generally use a SwingWorker to do this kind of thing but you can also do the manual approach outlined above.
SwingWorker provides a doInBackground method where you would stick your download logic in, a done method where you would stick in code to notify the GUI that the download finished and a get method to get the result of doInBackground (if there was one).
E.g.,
class Downloader extends SwingWorker<Object, Object> {
#Override
public Object doInBackground() {
return doDownload();
}
#Override
protected void done() {
try {
frame.downloadDone(get());
} catch (Exception ignore) {
}
}
}
(new Downloader()).execute();

Java thread trobleshooting for SwingWorker like tasks

Thread dump contains wealth of information. For example, if I suspect some action fired more than once, then all I need to do is dumping stack trace each time the action is fired, then investigate the stacks for erroneous action firing.
In certain situations developers are encouraged to abandon conceptual simplicity of sequential execution. For example, Swing offers SwingWorker helper to work around limitations of single threaded EDT. Now, if I dump stack trace, it is useless, because the action is fired by SwingWorker, and there is no information on who initiated SwingWorker task.
So, how do I troubleshoot? Is there a clever trick of "redirecting" thread dump to follow the genuine cause?
You can extend SwingWorker to record the stack when it is created (or when execute but then you need to create another execute method since it is final). Creating the cause is relative expensive though so you might want to do it only when debug (check log level or some such)
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
public abstract class TracedSwingWorker<T, V> extends SwingWorker<T, V> {
private final Exception cause;
public TracedSwingWorker() {
super();
this.cause = new Exception("TracedSwingWorker created at:");
}
#Override
protected final T doInBackground() throws Exception {
try {
return doWorkInBackground();
}
catch(Exception e) {
if(this.cause != null) {
Throwable cause = e;
while(cause.getCause() != null) {
cause = cause.getCause();
}
cause.initCause(this.cause);
}
throw e;
}
}
protected abstract T doWorkInBackground();
// just for testing
public static void main(String[] args) {
new TracedSwingWorker<Void, Void>() {
#Override
protected Void doWorkInBackground() {
throw new IllegalArgumentException("Exception in TracedSwingWorker!");
}
#Override
protected void done() {
try {
get();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
}
}.execute();
}
}
prints:
java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException: Exception in SwingWorker!
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
<snip>
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.Exception: SwingWorker created at:
at TracedSwingWorker.<init>(TracedSwingWorker.java:15)
at TracedSwingWorker$2.<init>(TracedSwingWorker.java:60)
at TracedSwingWorker.main(TracedSwingWorker.java:60)
I might be telling you something you already know but I suggest ThreadDump
http://www.oracle.com/technetwork/java/javase/tooldescr-136044.html#gbmpn
If you use IDE, then this is good:
NetBeans
http://netbeans.org/kb/docs/java/debug-multithreaded.html
I used Eclipse for this a lot. Debugger view has means of visualizing and tracking multiple threads, printing stack and pausing them.

tomcat cannot reload context because of a background thread

I have a JSF2 project with Spring. It is developed on eclipse with tomcat attached to it. It is pretty straight forward and mostly with default settings.
But, we have a few background threads that look like this:
public class CrawlingServiceImpl implements CrawlingService, InitializingBean{
private final Runnable crawlingRunnable = new Runnable() {
#Override
public void run() {
//...
}
};
public void startCrawling() {
crawlingThread = new Thread(crawlingRunnable);
crawlingThread.start();
}
public void stopCrawling(){
if ( crawlingThread!=null )
crawlingThread.interrupt();
crawlingThread = null;
}
#Override
public void afterPropertiesSet() throws Exception {
startCrawling();
}
public void destroy(){
stopCrawling();
}
}
Here's who's calling the destroy() method:
<bean
id="crawlingService"
class="com.berggi.myjane.service.CrawlingServiceImpl"
autowire="byName"
scope="singleton"
destroy-method="destroy"/>
I know that there is a better way all this to be done. But this is not my code and I don't want to rewrite it.
My problem is the following:
When I change a class (every single time) or when I change an xhtml file (very rarely) the server attempts to reload it, but it fails with the following errors:
INFO: Illegal access: this web application instance has been stopped already. Could not load org.apache.xml.dtm.ref.DTMManagerDefault. The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
java.lang.IllegalStateException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1562)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at org.apache.xml.dtm.ObjectFactory.findProviderClass(ObjectFactory.java:508)
...
at package.CrawlingServiceImpl.crawl(CrawlingServiceImpl.java:92)
at package.CrawlingServiceImpl$1.run(CrawlingServiceImpl.java:39)
at java.lang.Thread.run(Thread.java:680)
Note: Check the stacktrace. There are a lot of these exceptions.
Then there are more exceptions for a missing jdbc driver which is absolutely fine.
Any ideas?
are you sure crawlingThread.interrupt(); is killing the running of the Thread.
Without seeing the code of run(). it looks like it probably has a method called crawl and it does 1 of 2 things
1) a loop which expects a boolean variable to stop it running, and some possible sleeps/waits. I see an interupt, but no boolean being set to terminate the threads loop.
2) it runs once (no loop) and when finished dies - however, I don't see how the interupt will help here.
Assigning the Thread variable to null will not help to kill the thread.
if you want a quick fix, you could try set the thread to a daemon thread to allow it to be terminated.
private final Runnable crawlingRunnable = new Runnable() {
{
setDaemon(true);
}
#Override
public void run() {
//...
}
};
//...
}
But without the code, I'd guess the thread is refusing to die properly due to either issue 1 or 2.

Categories