Annotation called ThreadSafe - java

#ThreadSafe
public class A
{
}
Does this annotation actually make the class Thread Safe or is it just for readability?

See #ThreadSafe Annotation:
Place this annotation on methods that can safely be called from more
than one thread concurrently. The method implementer must ensure
thread safety using a variety of possible techniques including
immutable data, synchronized shared data, or not using any shared data
at all.
It does not make the class Thread Safe, the programmer does it Thread Safe and adds the annotation.
You might want to see this helpful link too.

The #ThreadSafe annotation is used:
to express the thread safety guarantee to the users of the annotated class, so that they can quickly understand whether they should use this class in a multi-threaded environment. Perhaps more importantly, it gives them guarantee that this will also be true in the future.
for the maintainers of the code to be aware that their changes must not break the thread safety promise. This is important because client code may depend on this class being thread-safe.
by IDEs and static analysis tools to help you identify potential concurrency-related problems when using this class.
The annotation does not change the way the code itself operates, and putting it on a class that does not guarantee thread safety is a mistake.

Related

Condition Interface in Java

I'm trying to write some classes that implements the java.util.concurrent.locks.Lock interface, one of the methods that should be overridden is condition that returns a condition associated with the lock.
Is there an implementation for the java.util.concurrent.locks.Condition interface that I can use? Writing one by myself seems like a hard task
The sources for implementations of these interfaces are all in the OpenJDK source tree. The code in AbstractQueuedSynchronizer is where the heavy lifting occurs. However, I doubt you can extract the Condition code from here and just use with your Lock implementation. My guess is that the code for locks and conditions is fairly mutually dependent.
If you only need to support mutual exclusion but not conditions, you don't have to implement them. The newCondition method says that support for conditions is optional, and this method is allowed to support UnsupportedOperationException. The ReentrantReadWriteLock.ReadLock class is an example of a lock that doesn't support conditions.

Thread safe class vs Utility class with all static methods

When ever I see a class documented as thread safe, I wonder why it was not designed to be a utility class with all static methods like java.lang.Math, etc.
I'm missing valid driving force whenever I design a class in the scenarios like no state but chained methods in a single class.
Example 1: How about a class A that has a 'thread-safe field' S; I mean, the object 'S' itself is thread-safe. Can we declare all the methods and fields like S in class A to be static.
I hope my explanation is clear enough. Please clarify.
Note: Exclude javabeans, property holding classes, etc.. My question was regarding classes which perform some actions based on input params, they might need to make use of other classes as well.
I apologize that I edited the question. First draft was totally ambiguous.
I can easily imagine a situation where a class is required to have state, yet it's also a requirement to be thread-safe. I use queues for worker-threads for example. It HAS to be thread-safe and definitely has to have state in it. (namely the elements in the queue)
EDIT:
Note: Exclude javabeans, property holding classes, etc.. My question was regarding classes which perform some actions based on input params, they might need to make use of other classes as well.
If by that you mean that your question is about truly stateless classes, then -by definition- your observation is correct. Those can almost always be expressed in static utility classes.
EDIT2:
I think you are being somewhat mislead by the fact, that a lot of times when we see static we can relax about thread-safety. (Though it's not true in every case, just a rule of thumb) While thread-safety and statelessnes can go hand in hand in a way, static is an orthogonal concept. Furthermore, statelessnes does give you thread safety but thread safety doesn't have to mean stateless. If that would be the case, the whole concept of synchronized would be unnecessary.
For testability and since static fits OO like fist fits nose.
Testable code requires that you can CREATE your tested object in a controlled way. I don't want to have to execute someone's code just because it's called from somewhere within object I'm testing. I want to test my object in isolation - assuming it's collaborators work fine. Using static methods from some tools makes me use PowerMock for testability OR kiss isolation good-bye and execute that code as well while I'm testing. Powermock is a problem (since it uses it's own classloader), so is testing more than I want.
Static means procedural code. That's fine sometimes, since procedural is fine sometimes. But try to use OO features (inheritance, polymorphism) with static methods to find another reason when NOT to use static.
Simple example illustrating this: http://www.javaworld.com/javaworld/javaqa/2001-05/01-qa-0504-oo.html?page=1 - by no means exhaustive, but shows the point I hope.
Other examples are listed in #JB Nizet's comment on the answer above.
I know this is a late answer, but honestly, I had my fair share of problems with testing objects using static methods from 'instanceless' classes and the usually sought-after solution aka PowerMock.

Is there any compile-time mechanism in Java to attempt to ensure that use of a particular class is always synchronized?

We have a class in our codebase currently that uses the synchronized keyword at the method level to ensure data consistency in multithreaded operations. It looks something like this:
public class Foo
{
public synchronized void abc() { ... }
public synchronized void def() { ... }
//etc.
}
The nice thing about this is that anyone using the class gets the synchronization for free. When you create an instance of Foo, you don't have to remember to access it inside of a synchronized block or anything like that.
Unfortunately, it seems that synchronization at the method level isn't going to cut it anymore. Instead we're going to have to start synchronizing on Foo itself. I don't think anything like java.util.concurrent.AtomicReference is going to cut it either. I want to make sure no one else touches an instance of Foo while a particular (and possibly somewhat lengthy) operation is going on. So now we're going to have blocks like this in the code:
Foo foo = new Foo(); //this got created somewhere
//somewhere else entirely
synchronized(foo)
{
//do operation on foo
foo.doStuff();
foo.doOtherStuff();
}
So the main thing I'm worried about is that a few developers and I share this code. Foo objects are fairly ubiquitous. Since we're not getting the synchronization for free any more at the method level, we must ALWAYS remember to access a Foo object within a synchronized block.
So my question is, is there any mechanism (built-in or third party) in Java to allow me to generate warnings or errors at compile-time if an instance of Foo is accessed outside of a synchronized block?
Ideally it would be something I can either do to the class declaration (made up example below):
#EnsureSynchronized
public class Foo
{
//etc.
}
Or something I could do when I declare instances of Foo (made up example below):
#EnsureSynchronized
private Foo foo;
I know if I really wanted to I could probably write a custom FindBugs or PMD rule to do this, but I was hoping something like this already existed.
So I ask you, SO community, if you were in this situation, how would you try to ensure that Foo objects are only ever accessed and modified inside synchronized blocks?
Findbugs is pretty good at finding inconsistent synchronization so as long as you have some code that synchronizes all accesses to an object, and run findbugs, it should alert you to failures to sync.
A typical bug matching this bug pattern is forgetting to synchronize one of the methods in a class that is intended to be thread-safe.
You can select the nodes labeled "Unsynchronized access" to show the code locations where the detector believed that a field was accessed without synchronization.
Note that there are various sources of inaccuracy in this detector; for example, the detector cannot statically detect all situations in which a lock is held. Also, even when the detector is accurate in distinguishing locked vs. unlocked accesses, the code in question may still be correct.
If that isn't sufficient, you can always annotate with net.jcip.annotations.NotThreadSafe which findbugs recognizes.
From Chapter 10. Annotations :
FindBugs also supports the following annotations:
...
net.jcip.annotations.NotThreadSafe
If you want the check to be at compile time, FindBugs and PMD won't do. I would suggest Java's Annotation Processing Tool (APT). It will let you create a custom annotation processor that can add checks to the compilation process for uses of your annotated classes and cause compiler warnings or errors if your synchronization requirements are not met. In fact, you could even use it tamper with the code to add the synchronization during the compilation if it isn't already there.
To use the annotation processor you create, you just need to make sure it's on the classpath when you compile your project. No extra automated analysis needed.
If you call notify() without a synchronized block around it or the method being synchronized you will get an IllegalMonitorStateExcept (see the documentation). However, doing it is very hacky and should, if at all, only be used for debugging and not in a production setting.
At runtime you may use Thread.holdsLock().
Have you thought about inheriting from Foo, like SynchronizedFoo and using that in your code while others may still use Foo as needed?

questions around synchronization in java; when/how/to what extent

I am working on my first mutlithreaded program and got stuck about a couple of aspects of synchronization. I have gone over the multi-threading tutorial on oracle/sun homepage, as well as a number of questions here on SO, so I believe I have an idea of what synchronization is. However, as I mentioned there are a couple of aspects I am not quite sure how to figure out. I formulated them below in form of clear-cut question:
Question 1: I have a singleton class that holds methods for checking valid identifiers. It turns out this class needs to hold to collections to keep track of associations between 2 different identifier types. (If the word identifier sounds complicated; these are just strings). I chose to implement two MultiValueMap instances to implement this many-to-many relationship. I am not sure if these collections have to be thread-safe as the collection will be updated only at the creation of the instance of the singleton class but nevertheless I noticed that in the documentation it says:
Note that MultiValueMap is not synchronized and is not thread-safe. If you wish to use this map from multiple threads concurrently, you must use appropriate synchronization. This class may throw exceptions when accessed by concurrent threads without synchronization.
Could anyone elaborate on this "appropriate synchronization"? What exactly does it mean? I can't really use MultiValueMap.decorate() on a synchronized HashMap, or have I misunderstood something?
Question 2: I have another class that extends a HashMap to hold my experimental values, that are parsed in when the software starts. This class is meant to provide appropriate methods for my analysis, such as permutation(), randomization(), filtering(criteria) etc. Since I want to protect my data as much as possible, the class is created and updated once, and all the above mentioned methods return new collections. Again, I am not sure if this class needs to be thread-safe, as it's not supposed to be updated from multiple threads, but the methods will most certainly be called from a number of threads, and to be "safe" I have added synchronized modifier to all my methods. Can you foresee any problems with that? What kind of potential problems should I be aware of?
Thanks,
Answer 1: Your singleton class should not expose the collections it uses internally to other objects. Instead it should provide appropriate methods to expose the behaviours you want. For example, if your object has a Map in it, don't have a public or protected method to return that Map. Instead have a method that takes a key and returns the corresponding value in the Map (and optionally one that sets the value for the key). These methods can then be made thread safe if required.
NB even for collections that you do not intend to write to, I don't think you should assume that reads are necessarily thread safe unless they are documented to be so. The collection object might maintain some internal state that you don't see, but might get modified on reads.
Answer 2: Firstly, I don't think that inheritance is necessarily the correct thing to use here. I would have a class that provides your methods and has a HashMap as a private member. As long as your methods don't change the internal state of the object or the HashMap, they won't have to be synchronised.
It's hard to give general rules about synchronization, but your general understanding is right. A data-structure which is used in a read-only way, does not have to be synchronized. But, (1) you have to ensure that nobody (i.e. no other thread) can use this structure before it is properly initialized and (2) that the structure is indeed read-only. Remember, even iterators have a remove method.
To your second question: In order to ensure the immutability, i.e. that it is read-only, I would not inherit the HashMap but use it inside your class.
Synchronization commonly is needed when you either could have concurrent modifications of the underlying data or one thread modifies the data while another reads and needs to see that modification.
In your case, if I understand it correctly, the MultiValueMap is filled once upon creation and the just read. So unless reading the map would modify some internals it should be safe to read it from multiple threads without synchronization. The creation process should be synchronized or you should at least prevent read access during initialization (a simple flag might be sufficient).
The class you descibe in question 2 might not need to be synchronized if you always return new collections and no internals of the base collection are modified during creation of those "copies".
One additional note: be aware of the fact that the values in the collections might need to be synchronized as well, since if you safely get an object from the collection in multiple thread but then concurrently modify that object you'll still get problems.
So as a general rule of thumb: read-only access does not necessarily need synchronization (if the objects are not modified during those reads or if that doesn't matter), write access should generally be synchronized.
If your maps are populated once, at the time the class is loaded (i.e. in a static initializer block), and are never modified afterwards (i.e. no elements or associations are added / removed), you are fine. Static initialization is guaranteed to be performed in a thread safe manner by the JVM, and its results are visible to all threads. So in this case you most probably don't need any further synchronization.
If the maps are instance members (this is not clear to me from your description), but not modified after creation, I would say again you are most probably safe if you declare your members final (unless you publish the this object reference prematurely, i.e. pass it to the outside world from the cunstructor somehow before the constructor is finished).

Are all Java Properties' methods fully synchronized?

I know that the Properties class is a sub-class of Hashtable. So all the inherited methods are synchronized, but what about the other methods of Properties such as store, load, etc? (Dealing specifically with Java 1.6)
the java1.6 javadoc says:
This class is thread-safe: multiple
threads can share a single Properties
object without the need for external
synchronization.
I always found the doc disclaimer misleading, specially for beginners (pardon if it is not your case).
This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization.
Even Thread-safe classes need synchronization more than you think. What is synchronized on that classes are their methods, but often a user uses this classes in a more complex context.
If you only put/get it is ok, but with some more code things get tighter:
p.putProperty("k1","abc");
p.putProperty("k2","123");
String.out.println(p.get("k1")+p.get("k2"));
This example code only prints for shure "abc123" in a multi threaded environment, if the section is a synchronized block (and even then things could get wrong).
For that reason (and of courrse performance) i prefer non thread safe classes and i get forced to think: is my program thread safe ...

Categories