0

As far as i know, FacesContext is avalible only in request scope. I've created a thread that tries to receive instance of FacesContext, but it is returning null.

My point is to update some application-scoped beans every 10 seconds.

Thread's run method:

@Override
public void run()
{
    while (true)
    {
        try
        {
            TimeView timeView = (TimeView)FacesContext.getCurrentInstance().
                    getExternalContext().getApplicationMap().get("timeView"); 
            // FacesContext.getCurrentInstalce() returns null

            timeView.update();
            Thread.sleep(10000);
        }
        catch (InterruptedException ex)
        {
            System.out.println(ex);
        }
    }
}

TimeView's header (I've skipped getters/setters):

@ManagedBean(eager=true, name="timeView")
@ApplicationScoped
public class TimeView implements Serializable
{
    private int hour;
    private int minutes;
    private int seconds;

    public TimeView()
    {
        update();
    }

    public void update()
    {
        Date date = new Date();
        setHour(date.getHours());
        setMinutes(date.getMinutes());
        setSeconds(date.getSeconds());
    }

faces-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

    <managed-bean>
        <managed-bean-name>timeView</managed-bean-name>
        <managed-bean-class>foogame.viewBeans.TimeView</managed-bean-class>
        <managed-bean-scope>application</managed-bean-scope>
    </managed-bean>
</faces-config>

So, is there a way to receive refference to my application-scoped beans in this thread?

Adrian Adamczyk
  • 3,000
  • 5
  • 25
  • 41

1 Answers1

1

As there is now way to access/construct FacesContext outside of Servlet environment, I recommend you to pass the application scoped object to the constructor of the worker thread (the thread that performs the batch job). Updating the reference in the thread will result in updating the application scoped reference because they both point to the same instance.

If you have an EJB3 environment you could use EJB timer + @Singleton bean without the need to deal with threads and scopes.

Adrian Mitev
  • 4,722
  • 3
  • 31
  • 53