Accessing boolean in a multithreaded environment [duplicate] - java

This question already has answers here:
Multithreading and booleans
(2 answers)
Closed 9 years ago.
If I have a class holding a private boolean made public by a setter and getter method
, would I have to set those methods as synchronized if I want to read and write to
that boolean from different threads?

Synchronizing access of a simple value is often unnecessary. Generally all you need is to mark it volatile which is less restrictive and more informative.
It all really depends a lot on how you access the value.
In some cases using an AtomicBoolean can be the best approach. This provides slightly different guarantees to volatile.
See question Java: volatile boolean vs AtomicBoolean question for more details.

Taking a look at the classes in java/util/concurrent/atomic might be useful to you. Such as AtomicBoolean.

Yes, making setters and getters synchronized is a good idea. To read or write a boolean is NOT atomic command , so in rare cases it may cause you some problems. ( you cannot be sure if you reading form RAM or cashe). Unless it is volatile.

Related

Use case for non-final static variable [duplicate]

This question already has answers here:
Best Practice: Java static non final variables
(7 answers)
Closed 9 years ago.
After a couple of years using Java i've just realized that i don't understand what it the use case for non-final static variables. Can someone give me some hints or any example?
Maybe they are needed to be used in static methods? ... or useful to be shared between all instances?
What concerns me is they can be accessed and modified asynchronously by any subclass, or through any instance.
Thanks.
** note **
Sorry about duplication. I did my search before posting and i didn't find it.
As constants they have no use, which I believe is your main trails of thoughts are concentrated around.
But how do you think a static class is going to perform it's operations if there is any need for class scope variables that need to be shared across the method calls?
Or there are instances where data need to be stored in a static class etc.
There are a lot of use cases if you just stop to think about it.

String immutability and wait method in synchronized block [duplicate]

This question already has answers here:
Why is the String class declared final in Java?
(16 answers)
Closed 9 years ago.
I am new to Java and while I was reading through Java language I got into two doubts. Though I referred many websites and but still I am not very clear.
Why string class is immutable ? I saw some examples with new File(str) which leads to security threat, but I don't understand how if string is immutable, it will help this scenario.
Another doubt is why wait, notify and notifyall should be inside synchronized block. I know if not it throws illegalMonitorException. But I want to know the technical background why it should be in synchronized block and why not without in synchronized block wait and notify can have same behavior.
Why string class is immutable?
The question of why strings are immutable in Java is an old one, and it's been much debated. In my book, I'd say they are immutable because they should be immutable ;). That might sound like a cop out, but let me explain.
Most simply, strings are used all over the place, if they were mutable that would require a lot of baggage everywhere for making defensive copies and dealing with synchronization and so on. Making them immutable, and then having helpers for mutating them like StringBuilder/StringBuffer is a much better design choice (and a common choice in several languages, not just Java).
Second, everything should be immutable, unless there is a very good reason to justify mutability. Many many problems disappear with immutable classes (esp. pertaining to concurrency). See Effective Java: "Classes should be immutable unless there's a very good reason to make them mutable. If a class cannot be made immutable, limit its mutability as much as possible."
Third, strings are used in the internals of Java, such as the class loading mechanism. Making them immutable makes internal processes simpler, and prevents some security issues. (Another example, String constants are "interned" in Java for performance reasons: http://en.wikipedia.org/wiki/String_interning, and this is, again, much more sane with an immutable type.)
All in all there were probably several reasons the designers chose to make strings immutable in Java and as a day to day programmer it helps you out (as do the utils around creating new strings, like StringBuilder).
Why wait, notify and notifyall should be inside synchronized block?
Here's some info on that one: wait(), notify() and notifyAll() inside synchronized statement.
Basically it makes no sense for a thread to "notify" or "wait" unless it already owns the object's monitor.
In general though, if you are new to Java, you might want to also look at some of the newer utils relating to concurrency in java.util.concurrent: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html. Often you can rely on these classes and avoid hand coding synchronization, which is notoriously difficult and error prone.

Final variables [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why would one mark local variables and method parameters as “final” in Java?
I used PMD in my code and it always tells me to make method local variables final. Can someone tell me how this effects the general performance apart from making the code more readable.
There's no effect on performance and it's debatable whether it's more readable. Java should have made variables final by default.
The biggest value of final is that it prevents programming errors. Regarding performance, I'd think the compiler can figure out the last write to a variable in most cases and do the necessary optimizations.

java :Why the Local variable should be declared final [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Why would one mark local variables and method parameters as “final” in Java?
I am using PMD to see the code violations.
Inside a webService Method, I have this below code
public ServiceRequest getData()
{
Status status = new Status();
// code
}
What PMD is suggesting me is that, this local variable status could be declared as final.
My question is, making it final would result in any performance improvements or if not what benefits the code could get?
Taken from the following article: http://www.javapractices.com/topic/TopicAction.do?Id=23
clearly communicates your intent
allows the compiler and virtual machine to perform minor optimizations
clearly flags items which are simpler in behaviour - final says, "If you are looking for complexity, you won't find it here."
This is also discussed in this question: Can excessive use of final hurt more than do good?
final indicates the local variable won't be changed. My feeling is that methods should be so short you should be able to easily understand them and so making the variable final may be a bit redundant.
I prefer to make fields final because making the whole class so short, is a serious limitation. Also fields can have thread safety issues which local variables do not.
I dont know about performance-benefits by making status final, but PMD is suggesting you this, because probably you are never writing on status after its first initialization.
So what you gain by making it final is just that your code is less error-prone - if you declare it final, you cant overwrite it by mistake...

Why is String final? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why is String final in Java?
I'm just wondering why java.lang.String is made final? Is it to prevent from being inherited? Why?
Yes indeed. This allows code in security managers and classloaders to work with the String type without having to worry that it's actually dealing with a malicious subclass that's specifically designed to trick it into allowing evil code through.
You should not be extending the string class. Just write your own methods in some other class that manipulate strings.
The reason is that the string class is a stable one which should not be tampered with as you may re-define some methods which would have unknown side effects on some other transactions.
Aside from security aspects that were already mentioned, I suspect performance was another important reason. For older JVMs especially final classes (where all methods are final by definition) made it much easier to inline code on-the-fly. And since String is one of most heavily used objects, which affects overall performance of many applications, this was seen as an area where improvements would have big overall effect.

Categories