Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to pass objects between classes in different threads?

Tags:

java

I have a Class "A" that is "runnable" and I make new objects out of Java unmarshallers. The MainGUI thread tries to access those instances by a get() that is already in the class "A". The instances that I created at class A, I made them static, so that they be available forever, but the problem when I get a new complete instance that has different properties, I have to compare the new instance with the previous's one data and keep the new one.

Is there a better way or design for that problem ?

How can I get the instances of Class "A" that are created at runtime without making them statics ?

Sample Code:

    public class SOAPMessagesFactory {

     private static GetCameraImageResponse                getCameraImageResponse;

// process here the msgs in another thread, not shown here in that snipped
     if (messageTag.equalsIgnoreCase("GetCameraImageResponse")) {
                try {
                    JAXBElement<GetCameraImageResponse> cameraImageResponse = unmarshaller.unmarshal(SoapBodyReader, GetCameraImageResponse.class);
                    getCameraImageResponse = cameraImageResponse.getValue();

                } catch (Throwable ex) {
                    ex.printStackTrace();
                }

            }

public GetCameraImageResponse getCameraImageResponse() {

    if (getCameraImageResponse != null) {
        return getCameraImageResponse;
    } else {
        return null;
    }

}
     // in main gui

 public void UpdateGUI() {

        GetCameraImageResponse cameraImageResponse = messageFactory.getCameraImageResponse();

}
like image 943
Andre Avatar asked Oct 22 '22 12:10

Andre


1 Answers

Try a Producer-Consumer pattern.

like image 77
Roman Avatar answered Nov 04 '22 20:11

Roman