4

Is synchronization needed in the case when I initialize a variable with a simple assignment and I don't care about the possibility of multiple initialization that could happen?

Like in this:

public class Something {

    private static volatile Collection<String> data;

    protected static Collection<String> data() {
        if (data == null) {
            final Set<String> dataToSet = new HashSet<String>();
            dataToSet.add("value 1");
            dataToSet.add("value 2");
            data = dataToSet;
        }
        return data;
    }
}
František Žiačik
  • 7,511
  • 1
  • 34
  • 59
  • Please rephrase your question properly ,and **NO** I don't think its needed if you don't think there is a possible of concurrently accessing the same data (variable). – Sainath S.R Oct 23 '14 at 07:15
  • 1
    I'll say no. Here is a good article about synchronize and volatile : http://www.javamex.com/tutorials/synchronization_volatile.shtml – ToYonos Oct 23 '14 at 07:20
  • 1
    I think that's ok cause even if more than one thread enter the if statement, you will obtain a 2 value set in data thanks to local variable dataToSet. – Martin Oct 23 '14 at 07:23
  • 1
    Not related to your question, but using the same name for a method and for a field can get very confusing. Best to use different names. – Dawood ibn Kareem Oct 23 '14 at 07:42
  • Although volatile is sufficient if data redundancy is not an issue here, I'd suggest to implement a 'real' singleton anyway! See http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java – isnot2bad Oct 23 '14 at 14:04

3 Answers3

3

Assignment operation is atomic. Next, you have the volatile modifier that ensures a happens-before relationship between reads / writes. So, Synchronization is not needed here.

Use Synchronization when you need to prevent other threads from corrupting your data (by locking on an object's monitor and making sure only one thread can enter the critical code block at the same time)

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

Though the Hashset is synchronized collection, when u operate on the return value of data() method, there is a possibility that you'll operate on two different HashSets.

One thread may evaluate this (if (data == null) ) true and wait for the processor time, In the meantime some other thread can evaluate if(data==null) true and it will go ahead and initialize the HashSet. after a while when the first thread gets the processor time, it will resume from where it stopped, the first thread will initialize the HashSet again (to point data variable to a different object). Meanwhile the second thread may be working on a different Hashset Object which is not the same where first Thread operates on.

Proceso
  • 567
  • 1
  • 6
  • 24
  • Thanks, I'm aware of this and am ok with it as there should be no manipulations on the hashset. Still, I should probably make the collection immutable. – František Žiačik Oct 23 '14 at 08:34
1

you don't need synchronize with static variables initialization .

but you do need synchronize when access static variables in multi-thread enviroment .

There are two point u should know about static variables :

  1. Unlike local variables, Static variables and methods are not thread-safe in Java. They are actually a common cause of various thread-safety issues in Java application. Since every object of a class has same copy of static variable, it needs to be guarded by class lock. That's why if you are using static variables then make sure to properly synchronized its access to avoid thread-safety issues including race conditions (the use of static variables is not thread-safe) .

  2. Static fields or variables are initialized when class is loaded into memory. They are initialized from top to bottom in the order they are declared in Java source file. So static fields are initialized in thread-safe manner .

I think this explanation is quite clear to ur question . hopes it will help ~ :D

Adams.H
  • 1,603
  • 4
  • 20
  • 29
  • why down votes? plz give a reasonable comment before doing it . – Adams.H Oct 23 '14 at 11:39
  • I didn't downvote, but I see several possible reasons: (1) "leetspeak" like "u" is frowned upon because decoding it distracts from the content, (2) the question you're answering is "should synchronize static variables", which is different from "do I need to synchronize on an assignment", (3) first you say static variables are not thread-safe, then you say static variables are initialized in a thread-safe manner - this isn't wrong, but it is confusing because in the first part, you do not say what operations are unsafe. HTH. – toolforger Nov 12 '18 at 15:31