In Java, do I need to synchronize simple assignment to static?
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;
}
}
java multithreading thread-safety locking synchronized
add a comment |
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;
}
}
java multithreading thread-safety locking synchronized
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 7:15
1
I'll say no. Here is a good article about synchronize and volatile : javamex.com/tutorials/synchronization_volatile.shtml
– ToYonos
Oct 23 '14 at 7: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 7:23
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 7:42
Although volatile is sufficient if data redundancy is not an issue here, I'd suggest to implement a 'real' singleton anyway! See stackoverflow.com/questions/70689/…
– isnot2bad
Oct 23 '14 at 14:04
add a comment |
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;
}
}
java multithreading thread-safety locking synchronized
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;
}
}
java multithreading thread-safety locking synchronized
java multithreading thread-safety locking synchronized
asked Oct 23 '14 at 7:10
František ŽiačikFrantišek Žiačik
5,7742144
5,7742144
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 7:15
1
I'll say no. Here is a good article about synchronize and volatile : javamex.com/tutorials/synchronization_volatile.shtml
– ToYonos
Oct 23 '14 at 7: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 7:23
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 7:42
Although volatile is sufficient if data redundancy is not an issue here, I'd suggest to implement a 'real' singleton anyway! See stackoverflow.com/questions/70689/…
– isnot2bad
Oct 23 '14 at 14:04
add a comment |
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 7:15
1
I'll say no. Here is a good article about synchronize and volatile : javamex.com/tutorials/synchronization_volatile.shtml
– ToYonos
Oct 23 '14 at 7: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 7:23
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 7:42
Although volatile is sufficient if data redundancy is not an issue here, I'd suggest to implement a 'real' singleton anyway! See stackoverflow.com/questions/70689/…
– isnot2bad
Oct 23 '14 at 14:04
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 7:15
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 7:15
1
1
I'll say no. Here is a good article about synchronize and volatile : javamex.com/tutorials/synchronization_volatile.shtml
– ToYonos
Oct 23 '14 at 7:20
I'll say no. Here is a good article about synchronize and volatile : javamex.com/tutorials/synchronization_volatile.shtml
– ToYonos
Oct 23 '14 at 7:20
1
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 7:23
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 7:23
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 7:42
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 7:42
Although volatile is sufficient if data redundancy is not an issue here, I'd suggest to implement a 'real' singleton anyway! See stackoverflow.com/questions/70689/…
– isnot2bad
Oct 23 '14 at 14:04
Although volatile is sufficient if data redundancy is not an issue here, I'd suggest to implement a 'real' singleton anyway! See stackoverflow.com/questions/70689/…
– isnot2bad
Oct 23 '14 at 14:04
add a comment |
3 Answers
3
active
oldest
votes
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)
add a comment |
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.
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 8:34
add a comment |
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 :
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) .
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
why down votes? plz give a reasonable comment before doing it .
– JasonHuang
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
thanks for your advice , It do helps .
– JasonHuang
Nov 14 '18 at 8:24
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26522937%2fin-java-do-i-need-to-synchronize-simple-assignment-to-static%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
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)
add a comment |
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)
add a comment |
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)
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)
answered Oct 23 '14 at 7:18
TheLostMind♦TheLostMind
31.7k85588
31.7k85588
add a comment |
add a comment |
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.
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 8:34
add a comment |
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.
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 8:34
add a comment |
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.
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.
answered Oct 23 '14 at 7:37
ProcesoProceso
3721322
3721322
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 8:34
add a comment |
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 8:34
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 8:34
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 8:34
add a comment |
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 :
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) .
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
why down votes? plz give a reasonable comment before doing it .
– JasonHuang
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
thanks for your advice , It do helps .
– JasonHuang
Nov 14 '18 at 8:24
add a comment |
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 :
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) .
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
why down votes? plz give a reasonable comment before doing it .
– JasonHuang
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
thanks for your advice , It do helps .
– JasonHuang
Nov 14 '18 at 8:24
add a comment |
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 :
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) .
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
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 :
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) .
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
edited Nov 14 '18 at 8:23
answered Oct 23 '14 at 8:04
JasonHuangJasonHuang
96511423
96511423
why down votes? plz give a reasonable comment before doing it .
– JasonHuang
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
thanks for your advice , It do helps .
– JasonHuang
Nov 14 '18 at 8:24
add a comment |
why down votes? plz give a reasonable comment before doing it .
– JasonHuang
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
thanks for your advice , It do helps .
– JasonHuang
Nov 14 '18 at 8:24
why down votes? plz give a reasonable comment before doing it .
– JasonHuang
Oct 23 '14 at 11:39
why down votes? plz give a reasonable comment before doing it .
– JasonHuang
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
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
thanks for your advice , It do helps .
– JasonHuang
Nov 14 '18 at 8:24
thanks for your advice , It do helps .
– JasonHuang
Nov 14 '18 at 8:24
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26522937%2fin-java-do-i-need-to-synchronize-simple-assignment-to-static%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
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 7:15
1
I'll say no. Here is a good article about synchronize and volatile : javamex.com/tutorials/synchronization_volatile.shtml
– ToYonos
Oct 23 '14 at 7: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 7:23
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 7:42
Although volatile is sufficient if data redundancy is not an issue here, I'd suggest to implement a 'real' singleton anyway! See stackoverflow.com/questions/70689/…
– isnot2bad
Oct 23 '14 at 14:04