Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from a thread ( in a Servlet)

I'm using the ServletContextListener to create a new thread.

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.concurrent.*;

    public class Port implements ServletContextListener {
        private ExecutorService executor;

        public void contextDestroyed(ServletContextEvent event) {
            executor.shutdown();

        }

        public void contextInitialized(ServletContextEvent event) { 
            // start task
            executor = Executors.newSingleThreadExecutor();
            executor.submit(new Task()); //task should implement Runnable!

        }
    }

Inside this thread I'm reading data from a serial port (SerialPortEventListener). The task.class should read out information from the serial port during the whole period in which the server is active. I've thrown this inside a thread because there can only be one instance that reads from the serial port; data should then be shared to all clients.

Now I would like to acces the data this thread is reading from the serial port.

Can this be done? And if yes then how?

like image 713
Thomas Avatar asked Dec 30 '25 18:12

Thomas


1 Answers

You could, for example, store the read data in a servlet context attribute. Then, from the other classes, you would get the attribute from the servlet context:

public void contextInitialized(final ServletContextEvent event) { 
        // start task
        executor = Executors.newSingleThreadExecutor();
        executor.submit(new Runnable() {
            @Override
            public void run() {
                String data = readFromPort();
                event.getServletContext().setAttribute("serialPortData", data); 
            }
        });
    }
}
like image 143
JB Nizet Avatar answered Jan 01 '26 08:01

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!