Indigenuity
Indigenuity

Reputation: 9740

Mutable static variable across multiple threads

I'm learning about threads in Java right now, along with all the concepts and keywords. I just learned the volatile keyword, and it raised some interesting questions in my mind for a project I'm working on. Say I have a class called Connector with a field like this:

    public static String DEFAULT_CONNECTION_TYPE = "UDP";

Say I'll be making lots of Connector objects on multiple threads, but each thread will be using different connection methods (like "TCP"). On the threads that will be using other connection types, if I don't want to explicitly declare it for every object, is there a way to change the DEFAULT_CONNECTION_TYPE on each thread? Is there a keyword that will make a variable thread-local, yet still static across that thread? Does that even make sense?

Upvotes: 0

Views: 3530

Answers (3)

Abhinav Sarkar
Abhinav Sarkar

Reputation: 23792

I do not recommend changing a static variable from multiple threads just to avoid carrying it in the class instance, but if that's what you want to do, see ThreadLocal.

The right way to do this is to make the connection type an instance field:

enum ConnectionType { UDP, TCP; }

class Connector {

    private static final ConnectionType DEFAULT_CONNECTION_TYPE = 
        ConnectionType.UDP;

    private final ConnectionType connectionType;

    public Connector(ConnectionType connectionType) {
        this.connectionType = connectionType;
    }

    public Connector() {
        this(DEFAULT_CONNECTION_TYPE);
    }
}

Upvotes: 6

Aviram Segal
Aviram Segal

Reputation: 11120

Check out ThreadLocal

Upvotes: 1

Related Questions