Jörg
Jörg

Reputation: 13

NullPointer on new InitialContext()

we are using JBoss EAP 6.2.4 and within a stateless session bean we send JMS messages to an WMQ-queuemanager.

our code is als follows:

@Stateless
@LocalBean
public class MessageSenderBean {

    private static ConnectionFactory connectionFactory;
    private static InitialContext initialContext;

    @EJB
    IntegrationPropertyBean ipb;

    Logger logger = Logger.getLogger(getClass());

    /**
     * Default constructor.
     */
    public MessageSenderBean() {

    }

    @PostConstruct
    public void postConstruct() {
        logger.debug(" MessageSenderBeanPostConstruct called");
        try {
            initialContext = new InitialContext();
            String connectionFactoryName = ipb.getProperty(
                    MessageSenderBean.class, "connectionFactory");
            connectionFactory = (ConnectionFactory) initialContext
                    .lookup(connectionFactoryName);

        } catch (NamingException e) {
            logger.error("Exception occurred: " + e.toString());
            logger.error(e);
        }

    }

    public String sendMessage(String queueName, String content) {
        String result = null;
        Connection connection = null;
        try {
            connection = connectionFactory.createConnection();
        } catch (JMSException e) {
            logger.error("Exception occurred: " + e.toString());
            logger.error(e);
        }

        // prüfen ob InitialContext leer
        try {
            if (initialContext == null)
                initialContext = new InitialContext();
        } catch (NamingException e) {
            logger.error("Exception occurred: " + e.toString());
            logger.error(e);
        }

after startup of the server the bean works perfectly for the first actions but after some time without any action the bean looses the initialContext and an addtional creation fails within the new InitialContext()

Any idea why?

Thanks Joerg

Upvotes: 0

Views: 210

Answers (1)

Gabriel Aramburu
Gabriel Aramburu

Reputation: 2981

Take in mind the following:

The InitialContext object is not synchronized, which means that an instance should not be accessed simultaneously by different threads. You have declared the initialContext variable as a class member (static), therefore , at some point different threads will use it simultaneously.

A simple solution is declare the attribute as an instance member.

<!-- language: java -->
private InitialContext initialContext;

Upvotes: 2

Related Questions