Accumulative Runnable in Swing Java - java

As part of learning SwingWorker I was going thru the source code where I noticed something called AccumulativeRunnable. From the comment of the AccumulativeRunnable class definition I understand when it is to be used, but when I check the example code few questions came in my mind.
Below is the comment and example code in AccumulativeRunnable abstract class.
An abstract class (AccumulativeRunnable) to be used in the cases where we need to perform some actions on an appendable set of data.
The set of data might be appended after the is sent
for the execution. Usually such Runnables are sent to the
EDT.
Usage example: Say we want to implement JLabel.setText(String text)
which sends string to the JLabel.setTextImpl(String text) on the EDT.
In the event JLabel.setText is called rapidly many times off the EDT
we will get many updates on the EDT but only the last one is
important. (Every next updates overrides the previous one.) We might
want to implement this in a way that only the last update is
delivered.
AccumulativeRunnable<String> doSetTextImpl =
new AccumulativeRunnable<String>()} {
protected void run(List<String> args)} {
//set to the last string being passed
setTextImpl(args.get(args.size() - 1));
}
}
void setText(String text) {
//add text and send for the execution if needed.
doSetTextImpl.add(text);
}
Questions
The abstract class AccumulativeRunnable implements Runnable.
That means AccumulativeRunnable class should implement the run
method right?. But I could see just protected abstract void
run(List<T> args);. How this could be an implementation of the
Runnable interface.
Why the add() method of AccumulativeRunnable class is
synchronized ?. Can someone explain this with an easy example or
with the example I provided above.
When the arguments inside the add() method of
AccumulativeRunnable class will be null ? Can someone explain this with an easy example or
with the example I provided above.
How the add() method receives an array (T... args) ?. Can someone
explain this with an easy example or with the example I provided
above.
In the above example when we call doSetTextImpl.add(text); it
calls the add() method of AccumulativeRunnable class. But how this
internally calling the run() method?. I mean who is calling our
implemented run() method internally.
Entire code in AccumulativeRunnable:
public abstract class AccumulativeRunnable<T> implements Runnable {
private List<T> arguments = null;
/**
* Equivalent to {#code Runnable.run} method with the
* accumulated arguments to process.
*
* #param args accumulated argumets to process.
*/
protected abstract void run(List<T> args);
/**
* {#inheritDoc}
*
* <p>
* This implementation calls {#code run(List<T> args)} mehtod
* with the list of accumulated arguments.
*/
public final void run() {
run(flush());
}
/**
* appends arguments and sends this {#code Runnable} for the
* execution if needed.
* <p>
* This implementation uses {#see #submit} to send this
* {#code Runnable} for execution.
* #param args the arguments to accumulate
*/
#SafeVarargs
#SuppressWarnings("varargs") // Copying args is safe
public final synchronized void add(T... args) {
boolean isSubmitted = true;
if (arguments == null) {
isSubmitted = false;
arguments = new ArrayList<T>();
}
Collections.addAll(arguments, args);
if (!isSubmitted) {
submit();
}
}
/**
* Sends this {#code Runnable} for the execution
*
* <p>
* This method is to be executed only from {#code add} method.
*
* <p>
* This implementation uses {#code SwingWorker.invokeLater}.
*/
protected void submit() {
SwingUtilities.invokeLater(this);
}
/**
* Returns accumulated arguments and flashes the arguments storage.
*
* #return accumulated arguments
*/
private synchronized List<T> flush() {
List<T> list = arguments;
arguments = null;
return list;
}
}

The answer is the following implementation of Runnable.run(). From the Compiler's view, run(List<T>) has nothing to do with the method declared by the interface, it's simply a different method with the (coincidentally) same name.
public final void run() {
run(flush());
}
In graphical environments, you have a lot of concurrency, and synchronized prevents the method to be called from two threads at the same time, otherwise you would create a so-called race condition, in which the "faster" thread's update to the list is simply lost. In this specific case this race condition could occur if synchronized was missing from add(T...) and two threads were trying to add the first element to the list at the same time.
Before the first element has been added via add(T). arguments is the list of all operations that have to be executed. If you create a new AccumulativeRunnable<T>, the arguments attribute will be null (See line 2) until the first element has been added.
T... is called a "varargs argument". This is basically just syntactical sugar, and allows you to call add in any of the following ways (For more information feel free to read this):
add(firstObject). This will internally convert the one object you supplied into an array of type T with only one element (firstObject).
add(firstObject, secondObject, thirdObject) and so on, with any number of arguments. All these arguments will be packed into a single array and supplied to the function.
add(objectArray) with objectArray being an actual array of type T. In this case, the internal variable arguments will simply reference the supplied array.
The answer is written in the quote you supplied:
Usually such Runnables are sent to the EDT.
EDT = Event Dispatch Thread, a "hidden" thread somewhere deep inside the Swing framework that deals with all the button clicks etc. Things that might trigger the run() method are e.g. a call to frame.paint() (Or however that method is called, I'm using JFX, so I'm not an expert on Swing), a button click, a mouse movement, etc.

Related

What is the reason behind this weird implementation of System.console()?

I stumbled upon the source code of System.console() and I'm unsure why exactly it is implemented like this:
/**
* Returns the unique {#link java.io.Console Console} object associated
* with the current Java virtual machine, if any.
*
* #return The system console, if any, otherwise {#code null}.
*
* #since 1.6
*/
public static Console console() {
Console c;
if ((c = cons) == null) {
synchronized (System.class) {
if ((c = cons) == null) {
cons = c = SharedSecrets.getJavaIOAccess().console();
}
}
}
return c;
}
More specifically, what is the point of the assignments to c? The variable cons is already static and holds the console object.
tl;dr: It’s a common optimisation technique.
This pattern is called double-checked locking.
The implementation could also just look much simpler, as follows:
public static synchronized Console console() {
if (cons == null) {
cons = SharedSecrets.getJavaIOAccess().console();
}
return cons;
}
However, that way we would always lock the entire System class for every single call of the console method, which would lead to a substantial slowdown in typical applications.
Instead, the actual implementation defensively locks the object only if it can’t acquire a valid cons instance. And it assigns the result to a local variable c so that this instance remains valid even if another thread overrides cons after the (unlocked) check happens. It also helps reduce reading the cons reference, which is declared as volatile, and reading it is thus slower than reading a non-volatile reference.

Is it possible to override a method comment but not the method?

I have methods toSaveString(StringBuilder) and toSaveString() in several classes and thought of turning those into an interface. The first method would always have to be implemented and the second I could default because it basically only calls the first method every time with a new string builder and returns the resulting string. (Not what default is designed for, but bear with me.)
Now I wouldn't need to implement toSaveString() in the classes implementing the interface, but I would like to change its documentation nonetheless to match the class. Is there a way to achieve this without overriding the toSaveString() method in the implementing class? Because adding three lines to call the default method or five to copy the implementation seems redundant and easy to get errors mixed in.
Also feel free to leave comments about design alternatives here, but the question stays because it is interesting in its own right.
Look at the javadoc of the ArrayList#removeIf method:
/**
* #throws NullPointerException {#inheritDoc}
*/
#Override
public boolean removeIf(Predicate<? super E> filter) {
return removeIf(filter, 0, size);
}
It overrides its superclass Collection#removeIf method:
/**
* Removes all of the elements of this collection that satisfy the given
* predicate. Errors or runtime exceptions thrown during iteration or by
* the predicate are relayed to the caller.
*
* #implSpec
* The default implementation traverses all elements of the collection using
* its {#link #iterator}. Each matching element is removed using
* {#link Iterator#remove()}. If the collection's iterator does not
* support removal then an {#code UnsupportedOperationException} will be
* thrown on the first matching element.
*
* #param filter a predicate which returns {#code true} for elements to be
* removed
* #return {#code true} if any elements were removed
* #throws NullPointerException if the specified filter is null
* #throws UnsupportedOperationException if elements cannot be removed
* from this collection. Implementations may throw this exception if a
* matching element cannot be removed or if, in general, removal is not
* supported.
* #since 1.8
*/
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
In your case, you can override only javadoc, and write something like this in the method body:
/**
* custom javadoc
*/
#Override
public boolean customMethod(Object parameter) {
return super.customMethod(parameter);
}
See also: Can I add code to an inherited method without overriding the whole method?

What is the difference between removeAllElements() and clear() for DefaultListModel?

What is the difference between removeAllElements() and clear() method of DefaultListModel in java swing?
The java docs for DefaultListModel says :-
public void clear()
Removes all of the
elements from this list. The list will
be empty after this call returns
(unless it throws an exception).
and
public void removeAllElements()
Removes all components from this list
and sets its size to zero.
So both basically removes all elements from list so what is the difference? How to decide when to use which?
They are both same.
DefaultListModel uses a Vector under the hood.
The clear() method was added later when Vector was re-written to fit into the Collection API's.
With version 1.3 the Collections API made its' entrance so the Vector was re-written to fit into the List interface.
In order for it to be backwards compatible, they simply forwarded the calls to the old existing methods where available & possible.
EDIT
From Java Source:
/**
* Removes all components from this list and sets its size to zero.
* <blockquote>
* <b>Note:</b> Although this method is not deprecated, the preferred
* method to use is <code>clear</code>, which implements the
* <code>List</code> interface defined in the 1.2 Collections framework.
* </blockquote>
*
* #see #clear()
* #see Vector#removeAllElements()
*/
public void removeAllElements() {
int index1 = delegate.size()-1;
delegate.removeAllElements();
if (index1 >= 0) {
fireIntervalRemoved(this, 0, index1);
}
}

How can I write a contract for an abstract method?

I am using contracts in my Java project. (Contract = doing checks at the start and end of methods)
I am wondering if there is a nice way/pattern to write a contract for a generic method. For example:
public abstract class AbstractStringGenerator{
/**
* This method must return a new line as it's last char
* #return string output
*/
public abstract string generateLine(String input);
}
What I want is a nice way to check that the output of generateLine satisfies the contract (in this case, that last char must be a new line char).
I guess I could do this (but I wonder if there is a better way);
public abstract class AbstractStringGenerator{
public string generateLine(String input){
string result = generateLineHook(input);
//do contract checking...
//if new line char is not the last char, then throw contract exception...
return result;
}
/**
* This method must return a new line as it's last char
* #return string output
*/
protected abstract string generateLineHook(String input);
}
Hope this is not too vague. Any help appreciated.
This looks like the place to use the Template Method design pattern. With the template method pattern, the general algorithm can be implemented and finalized in the abstract class, whereas some of the specifics can be implemented in the child classes.
In order to implement the Template method:
You'll need to finalize the algorithm, to control the subclassing behavior. By disallowing subclasses from overriding the template method via the final keyword, one can ensure that the sufficient checks can be implemented in the template to ensure that the invariants in the algorithm are held good.
You'll need to allow subclasses to override the behavior that can vary. The subclass can completely override this behavior, and such methods are usually abstract in the parent class, often serving as places where subclasses can implement hooks.
The Template method can be implemented in your example as
public abstract class AbstractStringGenerator{
// marked as final. Subclasses cannot override this behavior
public final String generateLine(String input){
String result = generateLineHook(input);
//do contract checking...
//if new line char is not the last char, then throw contract exception...
if(!result.endsWith("\n")){
throw new IllegalStateException("Result from hook does not contain new line");
}
return result;
}
/**
* This method must return a new line as it's last char
* #return string output
*/
protected abstract string generateLineHook(String input);
}
public class ConcreteStringGenerator{
/**
* This method overrides the beh
* #return string output
*/
protected String generateLineHook(String input){
return "blah\n";
}
}
It's exactly that. you must create your method and use a final modifier on it so nobody can rewrite the contract. In this method you check your contract and call an internal method (your generateLineHook(String)) there is nothing more to do.
I believe that is a nice wa to do it, just remember to add a "final" to the public method so sub-classes cannot override your checking.
I use code contracts regularly and sometimes there are well defined and self-describing methods that it's very difficult to write a contract for.
I dont know about Java (I assume youre using iContract or something), but in C#/Code Contracts I'd do:
Contract.Ensures(result[result.Length-1] == #"\n");
or something similar....
I'm not sure what you mean by there being a better way to do this.

eclipse add unimplemented methods including javadoc

When implementing an interface in eclipse, it has a really nice feature that lets you "add unimplemented methods", and it will generate the method stubs for the interface methods.
However, it does not bring along the method documentation from the interface methods, and I was wondering if there was a way to get eclipse to do that.
Here's what I want to happen. Let's say I had an interface like this:
public interface BaseInterface {
/**
* This method takes the given string parameter and returns its integer value.
*
* #param x the string to convert
* #return the integer value of the string
*
* #throws Exception if some error occurs
*/
int method1(String x);
}
Now I create a class called MyClass which implements this interface. What I want to happen is that when I say "Add Unimplemented Methods", I want my code to look like this:
public class MyClass implements BaseInterface {
/**
* This method takes the given string parameter and returns its integer value.
*
* #param x the string to convert
* #return the integer value of the string
*
* #throws Exception if some error occurs
*/
public int method1(String x) {
return 0;
}
}
Yup : these methods are generated using the code templates you wrote.
You'll have to go in "Window/Preferences -> Java/Code style/Code templates"
Then, in the list, select "Comments/overriding methods" and change the content with the one you found in "Comments/methods" :
/**
* ${tags}
*/
You can even think about adding an ${see_to_overridden} to have a direct link to original method. However, notice that a method with no javadoc will automatically inherit its javadoc from its overriden one, so such a template may generate less relevant doc than default behaviour.
You can achieve it by JavaDoc annotation. It is not Eclipse specific and will work in all build/doc generation tools:
/**
* My custom decumentation, and then the original one:
*
* {#inheritDoc}
*/

Categories