Sikor Sikor - 1 year ago 70
Java Question

Is it possible to share a variable between few threads but not all of them?

I am pulling data from 3rd party API and I was wondering if it is possible to share variables between some threads, but not all of them.


I have 2 users and I'm starting 2 threads for each user. Lets say threads A,B for user 1 and threads C,D for user 2. Now I need some sort of flag to inform threads when to stop (lets say total number of pages that were already read, which varies from user to user). The problem is, the flag has to be synchronized for 2 threads that belong to this specific user, but not other threads. I cannot modify user entity. Creating 2 flags is out of option because this is just an example and in reality there might be multiple users pulling their data.

Is this possible? If yes, then how?

Thanks for your time.

Answer Source

When you create your threads for the user, also create the flag that needs to be shared and pass it to the thread so they can use it and share the information.

Something like:

AtomicBoolean userFlag = new AtomicBoolean(false);
Runnable a = new UserRunnable(userFlag);
Runnable b = new UserRunnable(userFlag);
// run a and b

And UserRunnable:

public class UserRunnable implements Runnable {
    private final AtomicBoolean flag;
    // + constructor

    public void run() {
        // use the flag
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download