How to send variable between classes while multithreading

113 Views Asked by At

This a much simplified version of my multithreading project and its just a way to replicate the issue in a simpler way for easy understanding.

So I have two classes startSession.java and main.java

what I am trying to do is to send a variable from startSession.java to main.java and Im also using multithreading. However, the problem I am facing is that everytime I try to retrieve the variable inside main I get a null value.

Inside startSession theres the run method and Setter(setSessionKey(String sess)) and getter(getSessionKey()) methods. I hardcoded a variable to test.

The get method only works inside the run method but when I call getSessionKey() from inside main I get a null as seen below. However, this is only a problem when I am using multithreading. When I dont use multithreading and instead just call the run method from inside main, the variable Im looking for is no longer null.

My question is there a way to send a variable from startSession to main while using multithreading ?

thank you

startSession.java

public class startSession extends Thread {

    static String sessionKey;

    public void run() {
        String createdSession = "83248329";
        setSessionKey(createdSession);
        System.out.println("Inside run method: " + getSessionKey());
    }

    public String getSessionKey() {
        return sessionKey;
    }

    public void setSessionKey(String sess) {
        sessionKey = sess;
    }
}

main.java

package com.Server;

public class Main {

    static String session;

    public static void main(String[] args) throws InterruptedException {
        startSession startSession = new startSession();

        startSession.start();

        session = startSession.getSessionKey();
        System.out.println("Inside Main: " + session);
    }
}

with multithreading

enter image description here

without multithreading

enter image description here

1

There are 1 best solutions below

4
On BEST ANSWER

Use a BlockingQueue whereby the Thread (Producer) will add to the shared queue and the Main (Consumer) will block on the take

main

 public static void main(String[] args) throws Exception {

    // example only uses 1024 - check what is best for you
    BlockingQueue queue = new ArrayBlockingQueue(1024);

    StartSession producer = new StartSession(queue);

    ....
    System.out.println(queue.take());

startSession

   String createdSession= "83248329";
   queue.add(createdSession);

see https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html

and https://jenkov.com/tutorials/java-util-concurrent/blockingqueue.html