jsf - FacesContext.getCurrentInstance() returns null in Runnable class -
i trying facescontext
calling facescontext.getcurrentinstance()
in run()
method of runnable
class, returns null
.
public class task implements runnable { @override public void run() { facescontext context = facescontext.getcurrentinstance(); // null! // ... } }
how caused , how can solve it?
the facescontext
stored threadlocal
variable in thread responsible http request invoked facesservlet
, 1 responsible creating facescontext
. thread goes through jsf managed bean methods only. facescontext
not available in other threads spawned thread.
you should not have need in other threads. moreover, when thread starts , runs independently, underlying http request continue processing http response , disappear. won't able http response anyway.
you need solve problem differently. ask yourself: need for? obtain information? pass that information runnable
during construction instead.
the below example assumes you'd access session scoped object in thread.
public class task implements runnable { private work work; public task(work work) { this.work = work; } @override public void run() { // use work. } }
work work = (work) facescontext.getcurrentinstance().getexternalcontext().getsessionmap().get("work"); task task = new task(work); // ...
if need notify client e.g. thread's work finished, should looking different solution e.g. adding faces message or so. answer use "push". can achieved sse or websockets. concrete websockets example can found in related question: real time updates database using jsf/java ee. in case happen use primefaces, @ <p:push>
. in case happen use omnifaces, @ <o:socket>
.
unrelated concrete problem, manually creating runnable
s , manually spawning threads in java ee web application alarming. head following q&a learn caveats , how should done:
Comments
Post a Comment