Вопрос

I'm using java for about a month, and still am generally an amateur in programming, so feel free to correct me if I get something wrong. Maybe I'll provide some excess details, but I'm so confused right now that I can't decide what matters anymore.

So, I've been developing multi-threaded client-server application. All threads are using the same object, in which certain configuration values and shared loggers are stored; this object is initialized in server-thread and then passed as an argument to client-thread class constructor. First it was assumed that fields of that object are changed only once, when server starts, so concurrent access was nothing to worry about, but now it's required for some configuration values to be re-read from config file when it's modified, without having to restart the server.

The first idea that came to mind after some research was to make a synchronized method that would be called when some values from the class are requested, and would re-read those values if our config file changed since last access and return immediately otherwise, like this:

<This code is inside "config" class, instance of which is shared between threads>
private static long lastModified;
private static File configFile;

public class ChangingVariableSet
    {
    <changing variables go here>
    }

private synchronized void ReReadConfig
    {
    long tempLastMod = configFile.lastModified();
    if(lastModified == tempLastMod)
        return;
    <reread values here>
    lastModified = tempLastMod;
    }

public ChangingVariableSet GetValues()
    {
    ReReadConfig();
    <return necessary values>
    }

(The above code isn't tested, i just want to get the general idea across).

But I just didn't like the idea of blocking every single time the value is requested, since that seems expensive, and my application has a possibility of becoming pretty high-loaded with lots of threads in the future. So I had a "good" idea - to check if file is modified before locking and then inside the locked method again, to avoid locking at all whenever possible:

 public ChangingVariableSet GetValues()
    {
    if(lastModified == configFile.lastModified())
        ReReadConfig();
    <return necessary values>
    }

Ten minutes later I learned it's called double-checked locking and another ten minutes later my world crumbled twice after reading this article: first time when I learned it supposedly would not work due to internal CPU caching and second time when I read about operations on long/float types not being atomic. Or will it work after all, since no object creation is involved? And, since operations on long are non-atomic, would it really be enough to declare "lastModified" as volatile? If possible, I would prefer a proper explanation on why it will/will not work. Thank you in advance.

P.S: I know similar questions were already answered couple of times, and maybe it would be better to stop nitpicking and synchronize the whole "getValue" method rather than "ReReadConfig", but I'm striving to learn more about thread-safe programming and to see pitfalls in my own code to avoid something similar in the future. I also apologize for any possible grammar and spelling errors, I don't know English that well.


EDIT: First, I fixed a typo in last "if" clause. Second - warning, the above code is NOT thread-safe, do not use it! In method

 public ChangingVariableSet GetValues()
    {
    if(lastModified == configFile.lastModified())
        ReReadConfig();
    <return necessary values>
    }

In case file was updated in time span between if-check and value returning, thread B could start ReReadConfig BEFORE thread A starts returning values, resulting in a dangerous partial changes to necessary data. It seems the correct way of doing what I need without excessive blocking is using ReentrantReadWriteLock, however, I still want to use double-checking to avoid excessive (and expensive, file is assumed to be large XML) config re-reads:

<...>
private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static final Lock read  = readWriteLock.readLock();
private static final Lock write = readWriteLock.writeLock();

private void ReReadConfig
    {
    write.lock();
    long tempLastMod = configFile.lastModified();
    if(lastModified == tempLastMod)
        return;
    <reread values here>
    lastModified = tempLastMod;
    write.release();
    }

 public ChangingVariableSet GetValues()
    {
    if(lastModified == configFile.lastModified())
        ReReadConfig();
    read.lock();
    <get necessary values>
    read.release();
    <return necessary values>
    }

Now it at least looks thread-safe, but question remains open on depending on volatile "lastModified" variable when checking: I've read somewhere that volatile variables can't guarantee anything on non-atomic operations, and "long" type read/writes ARE non-atomic.

Это было полезно?

Решение

You want to use a ReadWriteLock. This does not block readers as long as there are no writers.

Другие советы

If you can organize the code in such a way that all your config data is in a single immutable object and there is a shared volatile reference to that object, then this will be thread-safe. This kind of use case is actually what the revision of volatile semantics was aiming for.

public static volatile Config config;

void rereadConfig() {
  if (modified)
    config = new Config(...);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top