I wrote a small HTTP server in Java and I have a problem passing static variables (server configuration: port, root, etc.) to the thread that handles requests. I do not want my thread to modify these variables and if it extends the server class, it will also inherit its methods which I don’t want.
I don’t want to use getters for reasons of performance. If I make the static members final, I will have a problem when loading their values from the config file.
here’s an example
class HTTPServer {
static int port;
static File root;
etc..
....
//must be public
public void launch() throws HTTPServerException {
loadConfig();
while (!pool.isShutdown()) {
....
//using some config here
...
try {
Socket s = ss.accept();
Worker w = new Worker(s);
pool.execute(w);
}catch () {...}
}
}
private void loadConfig(){ //reading from file};
...
other methods that must be public goes here
}
I also don’t want to have the worker as nested class. It’s in another package…
What do you propose?
You could put your config in a final AtomicReference. Then it can be referenced by your worker and also updated in a thread-safe manner.
Something like:
Make the new
ServerConfclass immutable:Then your worker can get a reference to the current config via
HTTPServer.config.get(). Perhaps something like:loadConfig()can set new config via something like:If it’s not important for all your config to change at the same time, you could skip the
ServerConfclass and useAtomicIntegerfor the port setting, andAtomicReference<File>for the root.