2

I'm using Properties in my code and I'm curious about multiple access. I'm in the following case :

public Class MClass{
    private static Properties dicoCategories = new Properties(myPropertyFile);
    public void changeProperties(){
        // changing properties and updating the file
    }
}

MyClass is instanciated multiple times and each instance can modify the property file . I guess I could manage this concurrency using temp files and locks, but I would prefer to use an already existing function. However, I found none. My question is : does the Property class manages concurrency a special way, or is there a multi-users equivalent ?

merours
  • 4,076
  • 7
  • 37
  • 69

4 Answers4

8

Although the Properties file is thread-safe, if you modify it using multiple invocations you still need to ensure thread safety. e.g.

properties.set(name, value);

is thread-safe, but

if (properties.get(name) == null)  {
   properties.set(name, value);
}

is not thread-safe without additional guards, and you should synchronise around such sequences.

It's not clear from your question whether your real issue is with multiple processes accessing this properties file, and if that is the case, then perhaps file locking is appropriate. See this question/answer for more info.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

According to the documentation:

This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization.

reto
  • 9,995
  • 5
  • 53
  • 52
1

According to the Java API, it is thread-safe:

http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html

This would mean that you're OK making changes from different threads concurrently. However I would run a simple concurrency test to be 100% sure. You can also go into the source file and see how Java handles it internally...

Martin
  • 3,018
  • 1
  • 26
  • 45
  • 1
    No test can make you 100% sure. Tests only help to find bugs and code-breaking changes. The last sentence, on the other hand, is wise. For thread-safety can have different meanings. – Gangnus Jul 08 '19 at 19:25
1

As per Java documention

This class is thread-safe: multiple threads can share 
a single Properties object without the need for external synchronization

So, answer is that you can use the Properties instance in multi-threaded environment. What you need to keep in mind is that if the updates to Properties are very frequently done, then, it is possible that your application can become slow due to implicit synchronization within Properties. However, if it is once in a while, then you should be fine.

Wand Maker
  • 18,476
  • 8
  • 53
  • 87