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.
Related
As per the Interface Segregation Principle
clients should not be forced to implement the unwanted methods of an interface
...and so we should define interfaces to have logical separation.
But default methods introduced in Java 8 have provided the flexibility to implement methods in Java interfaces. It seems Java 8 has provided the feasibility to enhance an interface to have some methods not related to its core logic, but with some default or empty implementation.
Does it not violate the ISP?
Good question. Definitely, it violates Interface Segregation Principle and I personally don't like the concept of default implementation because it spoils the beauty of interface design and a bit on exact polymorphism as well. If somebody is not aware of the concept of ISP then they will start design fat interfaces and will end up like everything packed in one interface. During code design, people will not think logically as well.
This will end up with code smells and I am sure those who don't know the concepts will start writing bad code. I believe default implementation is an unwanted feature as it will tend people to write smelly code.
The ISP will be violated if you intend to do so. You can segregate the interfaces to fulfill only single responsibility. The group of methods for a particular responsibility most probably will follow 80-20 rule. You can provide the default implementations for 40-50% of the methods out of 80% part. This 40-50% part will be the one which will be rarely used and hence defaults are ok. If interface fulfills single responsibility, they will rarely be too big, and most often will be in ISP.
No.
In fact, default methods can be a good way of providing additional useful functionality while avoiding violating ISP.
An excerpt from my longer answer here:
There are examples in the standard library of good uses default methods. One would be java.util.function.Function with its andThen(...) and compose(...) methods. ...
These default methods do not violate ISP, as classes that implement Function have no need to call or override them. There may be many use-cases where concrete instances of Function never have their andThen(...) method called, but that's fine – you don't break ISP by providing useful but non-essential functionality, as long as you don't encumber all those use-cases by forcing them to do something with it. In the case of Function, providing these methods as abstract rather than default would violate ISP, as all implementing classes would have to add their own implementations, even when they know it's unlikely to ever be called.
The quote in the OP is not quite accurate. The actual statement of the ISP is,
Clients should not be forced to depend upon interfaces that they do not use.
The client is the consumer of the interface, i.e. the caller of its abstract methods. The client is not the implementer of the interface. If we are following the dependency inversion principle, the client should not even know the concrete implementation of the interface.
The reasoning behind the ISP is not to save developers from implementing additional abstract methods. It is to save the caller of those methods from unnecessary transitive dependencies. Additional interface methods risk pulling in additional dependencies (via declaration or implementation). A client who doesn't use those methods still acquires those dependencies and becomes coupled to clients who do use those methods through the changes those clients force upon the interface and its shared implementation.
Applying this principle to default methods in Java 8, it is certainly possible for such a method to violate the ISP by adding dependencies that not all clients require. On the other hand, it is also possible (and preferable) for a default method to not add any dependency and to never change in any way that breaks clients.
In summary, default methods are just another tool. They may be used to help your code or to hurt it.
Are AtomicIntegers considered synchronization primitives, or is it just the methods provided by Java (wait(), notify(), etc).
I am confused about the definition of primitives, as atomicintegers can operate on int and provide lock free thread sage programming. Without the use of synchronized.
AtomicInteger is a class. Its methods are... well, methods. Neither one of those would be considered a synchronization primative.
The compareAndSet method, which is also used by incrementAndGet and other such methods, uses Unsafe.compareAndSwapInt (on OpenJDK 7, which is what I have handy). That's a native method — so it could well be considered a primitive. And in fact, on modern CPUs, it translates to a CAS instruction, so it's a primitive all the way down to the hardware level.
The class also relies on volatile's memory visibility, which is also a synchronization primitive.
I think this question is a bit "vague"; but I think that "language primitive" typically refers to language elements that are part of the core of the language.
In other words: the keywords, and the associated semantics. In that sense; I would see the synchronized (in its two meanings) and volatile keywords as being the only "primitive" regarding multithreading.
Of course, classes such as Object; and therefore all its methods like wait(), notify() ... are also an essential part of Java (one which you can't avoid in the first place). And of course, same can be said about the Thread class.
Long story short: you can differentiate between concepts that exist as language keywords (and are thus handled by the compiler); and "on-top" concepts that come as "normal" classes. And as the answer from yshavit nicely describes, certain aspects of AtomicInteger can be directly mapped into the "native" side of things. So the real answer is maybe that, as said, the term "primitive" doesn't provide much aid in describing/differentiating concepts regarding Java multi-threading topics.
Regarding your first query:
Are AtomicIntegers considered synchronization primitives, or is it just the methods provided by Java (wait(), notify(), etc).
No. AtomicInteger is neither a method nor synchronized primitive.
AtomicInteger is a class with methods. Have a look at oracle documentation page on atomic packages
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
boolean compareAndSet(expectedValue, updateValue);
The classes in this package also contain methods to get and unconditionally set values, as well as a weaker conditional atomic update operation weakCompareAndSet
Regarding your second query:
I am confused about the definition of primitives, as atomicintegers can operate on int and provide lock free thread sage programming. Without the use of synchronized.
One key note:
The scope of synchronized is broad in nature compared to AtomicInteger or AtomicXXX variables. With synchronized methods or blocks, you can protect critical section of code, whcih contains many statements.
The compareAndSet method is not a general replacement for locking. It applies only when critical updates for an object are confined to a single variable.
Atomic classes are not general purpose replacements for java.lang.Integer and related classes. However, AtomicInteger extends Number to allow uniform access by tools and utilities that deal with numerically-based classes.
#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.
I'm fairly new to programming against interfaces and am trying to get it right as a major tool for developing test driven.
Currently we have a lot of Manager classes that all implement a CRUD interface. However some Managers don't yet do updates and some don't do delete, some may never do so.
Not implemented exception?
Is it okay, to just
throw new NotImplementedException()
until the method gets implemented or even for all time if it never does?
(obviously with a source code comment telling the programmer "this method is not supposed to be used, as e.g. Types like 'male' 'female' do never get deleted)?
Split?
Or should I split my CRUD interface into Creatable, Readable(Searchable), Updatable and Deletable? Wouldn't that clutter my class definition?
PersonManager implements Creatable<Person>, Updateable<Person>, Deletable<Person>, Searchable<Person>
Split and combine?
Or should I combine some interfaces like all 4 into CRUD and maybe some other combinations like Read + Update?
Maybe that would also create a load of interfaces where one has to click through a big inheritence path to find out which interface implements all the desired atomic interfaces for the current situation (I need read and create, so which one just implements the two? and this can get a lot more complex quickly)
IMO, for the middle stage - it is OK to use NotImplementedException, until you finish implementing it.
However, as a permanentsolution - I believe it is a bad practice [in most cases].
Instead, I'd create an interface that contains behavior common to all implementing classes, and use subinterfaces to cluster them up for more specific behavior.
The idea is similar to java standard SortedSet, which extends a Set - we wouldn't want to regard Set as SortedSets and give a variable of this type a value of HashSet, instead we use a sub-interface, SortedSet for this purpose.
Generally you would like to throw UnsupportedOperationException which is a runtime exception, clearly mentioning that the requested operation is not supported.
Having loads of interfaces will lead to too many files and also if someone tries to look at them they will get confused. Java docs don't help much either in such cases.
Splitting interface makes sense if there are too many operations for one interface, and not all operations are logically binded together.
For database operation rarely its the case as you will have some basic operation which will be true for most of the scenario.
NotImplementedException doesn't mean that class doesn't support this action. It means it's not implemented, but it will be in the future.
From logical point of view all interface methods must be implemented, and must work well. But if you leave it, and write an application just for yourself, then you will remember about this limitation. In other hand I would be angry that some developer implemented interface and left it unimplemented. So I don't think you can leave interface method not implemented just for future development.
My suggestion is rather to modify interfaces, then use exceptions inside implemented methods.
In frameworks that support covariance and contravariance, it can be very useful to split up interfaces and then define some composite interfaces. For frameworks that do not offer such support, (and even sometimes on frameworks which do) it is sometimes more helpful to have an interface include methods which individual implementations may or may not support (implementations should throw an exception when unsupported actions are attempted); if one is going to do that, one should include methods or properties by which outside code can ask what actions are supported without needing to use any code that will throw an exception.
Even when using interfaces that where support for actions is optional, however, it may sometimes be helpful to define additional interfaces which guarantee that certain actions will be available. Having interfaces which inherit other interfaces without adding new members can be a good way to do this. If done properly, the only extra work this will require on behalf of implementations is to make sure they declare themselves as the most specific type applicable. The situation for clients is a little more complex: if clients' needs can be adequately expressed in the type system, clients can avoid the need for run-time type-checking by demanding specific types. On the other hand, routines that pass instances between clients may be complicated by some client's demands for more specific type than the instance-passing code itself would otherwise require.
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 ...