Djon
Djon

Reputation: 2260

Do I absolutely have to use static variables when working with threads?

As part of a personal project I am making an IRC bot. My first attempt was to have one main class do all the work, but it is not very efficient, so I decided to separate the IRC part from the bot, making a very simple IRC client that would connect to the server, authenticate itself, join the channels and receive lines.

I can then either process each line as the IRC client receives it or put the client in a thread where it will put the lines in a queue or map (depending on what type of line it is). The thread option seems to be more appropriate and challenging.

Since the bot needs to have access to the lines received by the IRC client, I thought of putting the lines in a public static queue accessible by the bot, but that reminds me a global variables in C and I find it very odd since everyone can access this field. Is there a way I could have the IRC client do its job and the bot peaking in the lines without a public static field?

I thought of having the IRC client deliver the lines with a synchronized method so the bot is notified when a line is available.

Upvotes: 2

Views: 138

Answers (1)

Stephen C
Stephen C

Reputation: 718668

You can share state between two (or more) threads without using static fields. For example:

    public class State {
        private final Queue queue = ...
        private final Object somethingElse =
        // getters and setters
    }

    public static void main(String[] args) {
        State state = ...
        new thread(new IRC(state)).start();
        new thread(new Bot(state)).start();
    }

Then define IRC and Bot classes to implement Runnable and provide them with constructors that take a State instance as an argument. Of course, operations on the shared state need to be suitably synchronized.

Upvotes: 3

Related Questions