how can i create many threads at JWT?

Added by Everton Fonseca about 5 years ago

example #1

new Thread(()->{

WContainer root = WApplication.getInstance().getRoot();

WContainer divMain = new WContainer(root);



//message out

Exception NullPointer --------- > Why?

Replies (2)

RE: how can i create many threads at JWT? - Added by Wim Dumon about 5 years ago

WApplication.getInstance() works by querying thread local storage for getting the WApplication that a thread is currently working on. Since you freshly created a thread, this TLS is not set.

Wt sets this TLS when it starts processing events for a particular application on a particular thread, so in many cases WApplication.getInstance() magically returns the WApplication you're working on. If you start your own thread, this is obviously not the case.

In addition, you can't just start working with a widget tree of an application from any thread. The WApplication object and its data (including the widget tree) is protected by a lock. This is the updatelock. Grabbing the update lock will also set the TLS, so that WApplication.getInstance() does no longer return null.

So WApplication.getInstance() returning null is a dead giveaway that you're doing something wrong: you should have grabbed the updatelock.

Also: when modifying the widget tree from a thread, you'll need to use server push to send the updates to the browser.