Re-define wait method in a Java interface - java

I would like to use wait(int) as the signature of a method in a fluent API (used for http://www.jooq.org). The goal is to be able to construct SQL queries like this example:
SELECT * FROM T_AUTHOR
WHERE ROWNUM <= 1
FOR UPDATE OF FIRST_NAME, LAST_NAME
WAIT 5
The full FOR UPDATE clause syntax specification (at least for Oracle) can be seen here:
FOR UPDATE [ OF [ [ schema. ] { table | view } . ] column
[, [ [ schema. ] { table | view } . ] column]...]
[ { NOWAIT | WAIT integer | SKIP LOCKED } ]
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/img_text/for_update_clause.htm
With jOOQ, I really want to stay close to the SQL syntax. So I'd like to be able to model the above SQL clause with the jOOQ fluent API like this:
Result<Record> result = create.select()
.from(T_AUTHOR)
.limit(1)
.forUpdate()
.of(FIRST_NAME, LAST_NAME)
.wait(5) // Here's the issue
.fetch();
The fetch method is used to render the API's underlying object as SQL and run the SQL statement against an Oracle (or any other) database. The above can be legally specified in an interface:
/**
* A type that models a "step" in the creation of a query using the fluent API
*/
public interface SelectForUpdateWaitStep extends SelectFinalStep {
// [...]
/**
* Add a "FOR UPDATE .. WAIT n" clause to the query
*/
SelectFinalStep wait(int seconds);
// [...]
}
I have some doubts about this, though, because there is a risk of collision with another method:
public class Object {
// [...]
public final native void wait(long timeout) throws InterruptedException;
// [...]
}
Thanks to method-overloading (int vs. long arguments), I can actually do this. But I'm afraid it might confuse my users and lead to mistakes. So this would be wrong:
.forUpdate()
.of(FIRST_NAME, LAST_NAME)
.wait((long) 5) // This doesn't make sense
.fetch(); // This doesn't compile
So my questions are:
Can I somehow prevent calling/accessing Object.wait(long) altoghether? I don't think so because it's declared final but maybe someone knows a compiler-trick, or something else?
Do you have a better idea for my API design apart from just renaming the method to something silly like doWait(int) or WAIT(int)?

You might try using a waitFor method instead, which specifies both a time and a "condition" to wait for. The implementation detail would be hidden, but one possible implementation would be to try your action immediately and loop until the specified condition has been met, with an appropriate pause between attempts.
Here's a sample interface for a Condition I use myself (as you can see, it doesn't need to be complex):
public interface Condition {
public boolean met();
}

void wait(long) is a part of the contract offered by Object and therefore it should not be changed. Imagine that someone stores your object and attempts to use it for wait/notify threading logic. So completely changing it's logic is just playing against the rules. So you will have to come up with different name.
On the other hand, it seems that having forUpdate take parameter indicating wait time will fit the bill. You could just have another version of forUpdate in addition to existing one.

What this requires is a way to disable an Object method. And main reason seems to be because it has a nice name that would fit the purposes of a proprietary API.
At first, this contradicts the entire idea of inheritance -- once you inherit from a class, all subclasses must expose the same non-private fields & method. You can always override a method, except when (1) it is marked as final and (2) it has an incompatible (non-covariant) return type, both of which are true with the void wait(long) method.
Furthermore, since every object is an Object in Java, everything must have a method void wait(long) and there should be no way to hide/delete/disable/forward/override it. Assuming it were possible to hide the void wait(long) method, how would you go about invoking it, should you wish to invoke it?
However, assuming you would never need to invoke void wait(long) for your particular classes, there is always the approach of source/byte-code weaving that AspectJ uses in order to make changes to the .class Java bytecode based on certain invocation rules. You could trap every call to wait(long) and declare an error/warning. See more here: http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations-decp.html
However, native method pointcuts are not possible even with AspectJ with byte-code weaving. Most likely, this is not possible even with source-code weaving -- but it might be worth a try.

Hacking around with core Java for the sake of DSL is simply not a good idea.
Why not make your DSL more expressive?
What does wait(int n) mean anyway? wait for N milliseconds, seconds, minutes?
A better signature would be:
wait(long duration, java.util.concurrent.TimeUnit){ ... }
which reads better, for example:
wait(30, TimeUnit.MILLISECONDS)

Related

Java store reflected Method statically in class: Safe?

Is something like the following 'safe' in Java, and why?
public final class Utility {
private Utility() {}
private static Method sFooMethod = null;
public static void callFoo(SomeThing thing) {
try {
if(sFooMethod == null)
sFooMethod = SomeThing.class.getMethod("foo");
sFooMethod.invoke(thing);
} catch(Exception e) {} // Just for simplicity here
}
}
My rationale would be that even if another thread writes to sFooMethod in the background and the current thread sees it suddenly somewhere during execution of callFoo(), it would still just result in the same old reflective invoke of thing.foo()?
Extra question: In what ways does the following approach differ (positive/negative) from the above? Would it be preferred?
public final class Utility {
private Utility() {}
private static final Method sFooMethod;
static {
try {
sFooMethod = SomeThing.class.getMethod("foo");
} catch(Exception e) {}
}
public static void callFoo(SomeThing thing) {
try {
if(sFooMethod != null)
sFooMethod.invoke(thing);
} catch(Exception e) {}
}
}
Background update from comment:
I am writing an Android app and I need to call a method that was private until API 29, when it was made public without being changed. In an alpha release (can't use this yet) of the AndroidX core library Google provides a HandlerCompat method that uses reflection to call the private method if it is not public. So I copied Google's method into my own HandlerCompatP class for now, but I noticed that if I call it 1000 times, then the reflective lookup will occur 1000 times (I couldn't see any caching). So that got me thinking about whether there is a good way to perform the reflection once only, and only if needed.
"Don't use reflection" is not an answer here as in this case it is required, and Google themselves intended for it to happen in their compatibility library. My question is also not whether using reflection is safe and/or good practice, I'm well aware it's not good in general, but instead whether given that I am using reflection, which method would be safe/better.
The key to avoiding memory consistency errors is understanding the happens-before relationship. This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement.
Java language specification states following:
17.4.5. Happens-before Order
Two actions can be ordered by a happens-before relationship. If one
action happens-before another, then the first is visible to and
ordered before the second.
If we have two actions x and y, we write hb(x, y) to indicate that x
happens-before y.
If x and y are actions of the same thread and x comes before y in
program order, then hb(x, y).
As, in your case, writing to and then reading from the static field are happening in same tread. So the `happens before' relation is established. So the read operation will always see effects of the write operation.
Also, all threads are going to write same data. At worse, all eligible threads will write to the variable same time. The variable will have reference to the object that got assigned last and rest of the dereferenced objects will be garbage collected.
There won't be many threads in your App which will enter the same method at once, which will cause significant performance hit due to lot of object creation. But if you want to set the variable only once then second approach is better. As static blocks are thread safe.
Is something like the following 'safe' in Java, and why?
No I would not recommend using reflections, unless you have to.
Most of the time developers design their classes in a way, so that access to a hidden field or method is never required. There will most likely be a better way to access the hidden content.
Especially hidden fields and methods could change their name, when the library they are contained in is updated. So your code could just stop working suddenly and you would not know why, since the compiler would not output any errors.
It is also faster to directly access a method or field then through reflections, because the reflections first need to search for it and the direct access don't
So don't use reflections if you don't have to
I'm not sure what your goal is -- there is probably a better way to do what you're trying to do.
The second approach, with a static initializer, is preferable because your first implementation has a race condition.

I need to use a Java 8 Optional method that either gets the wrapped value, or calls a void return Consumer lambda

I am new to using optionals in Java 8. I know the method orElseGet() takes a supplier and orElseThrow() also takes a supplier that throws an exception. orElseThrow() might be a good one to use if I can construct my own exception and do something when that exception is triggered.
My main goal is to use a method that will either get the unwrapped value, or if the optional wraps null, then to actually execute an entirely different function.
Looking for the closest thing to:
class DoInsteadClass {
public void doInstead() {
// Do this instead
}
}
Optional<String> myString = "Hello";
num.orElse(DoInsteadClass::doInstead);
If the only way to do this is orElseThrow(), and as long as I can handle the exception with the 'do this instead' code, that should be fine too. It just makes my codebase larger because I have to create a few different custom utility suppliers for the 2 or 3 cases where some of my optional values would return null.
The problem is, .ifPresent() invokes the specified consumer with the value, otherwise does nothing. I need it to DO SOMETHING if the value is null. My current code utilizes a custom workaround where I first check if the value is null, and if it is, execute a chosen function. Then the next statement is the one that checks for ifPresent(). So this is doing the same thing, I am just looking for a more sugar-coated, one statement version.
In JDK 9 there will be an ifPresentOrElse method that will allow it.
For the time being, however, you may opt for the if statement, with if(num.isPresent()), or write your own reusable ifPresentOrElse method.

Java : Best way to dynamically create method calling sequence

I have started working on a BDD project using JBehave. I need to build a sequence of methods to be called based on the steps "Given", "When" and finally execute them in "Then". A sample would be like
Given a user logins as a premium user
When he adds an item to the cart
Then he gets a special discount
For the above scenario, I would have to build method call sequence based on "Given" / "When" and then execute the same in "Then"
E.g.
List<Executable> sequenceList
#Given
public void execGiven()
{
A a = new A();
a.call1()
a.call2()
B b = new B();
b.call3();
}
#When
public void execWhen(){
C c = new C();
c.call4();
//...few more methods
#Then
public void execThen(){
//Add some methods to the list of executables
D d = new D();
d.call5();
Assert if everything successful
}
The problem I am facing is that the framework we are using(in built and in use) cannot be used to partially execute the method call sequences in each Step of a story. Rather, I have to execute them as a whole sequence( from a.call1 to d.call5).Also another issue is that I dont want to hardcode the method calls for each step instead call them based on some config at runtime.
My Approach.
Instead of running these methods (a.call1 , a.call2) in each step, add them to a list of Methods and execute them in "Then" using reflections. Also use annotations like
#Sequence(step="Login" , sequenceId=1) for each method so that at runtime I can build a list of calls to be made.
What would be a good approach considering that any change in the method call sequence is less painful to change. I had few approaches in mind
Use annotations to wire the sequence
Use xml to wire the sequence
Use a text file to mention the sequence(almost same as above)
Is there any better approach to build the graph in the runtime and execute the sequence? Also any drawbacks of the same?
Thank You

Queueing Methods With Java 8

I am building a game simulator that has hundreds of micro steps like the following. They each perform a unique task, but I left out the implementation details for the sake of brevity.
public class Sim {
static void phase() {
phaseIn();
phaseOut();
}
static void untap() {
}
static void upkeep() {
}
static void draw() {
}
...
}
A Turn usually involves executing steps sequentially, but there are times when a special effect may cause the sequence to change. For example, I may be required to repeat a step twice, skip a step, or rearrange the order of the steps. These actions are all special cases, as the turn typically just occurs in order from start to finish.
For example, the following series of events represents my normal turn.
... > upkeep() > draw() > preCombatMain() > ...
Now, I play something that requires me to repeat my draw step. I need my turn to look like this:
... > upkeep() > draw() > draw() > preCombatMain() > ...
The steps of a turn are methods, and I do not know how to enqueue or dequeue methods. I know that Java 8 has method references, but the feature is relatively new. I have been unable to apply existing tutorials to what I am trying to accomplish. I got as far as Sim::untap, but I have no idea how to assign it, invoke it, etc. How do I queue methods in Java 8, or otherwise call methods in an order determined at run-time by the choices a player makes?
Note: I realize that my inability to understand may be due to a fundamental design flaw. I have never taken a game design course, I am completely open to criticism, and I will change my design if it is flawed. That said, the question is not to be misconstrued as "Please recommend a design pattern." I considered an alternate design, where I "number" each step in a massive switch statement, queue "numbers", and repeatedly switch on the front of the queue, but that seemed like a poor plan (in my opinion).
If you simply want them to run sequentially, you can of course call them one after the other. If the order can change, an alternative is to use a queue of method references:
LinkedList<Runnable> queue = new LinkedList<>();
queue.add(Sim::upkeep);
queue.add(Sim::draw);
queue.add(Sim::preCombatMain);
queue.forEach(Runnable::run);
I was able to use a LinkedList<Runnable> because the signature of your methods is void m(). For other signatures you can use other types, for example:
void m() use Runnable
T m() use Supplier<T>
void m(T o) use Consumer<T>
R m(T o) use Function<T, R>
The solution is to use polymorphism. Define an interface for the step:
interface Step {
void process();
}
Then define each step by implementing it:
class UpkeepStep implements Step {
void process() { ... }
}
Now you can put all your steps in an array, shuffle it, if needed, and execute all steps, like this:
for (Step step : steps) {
step.process();
}
An alternative approach that may run faster, is to generate code that contains the method calls, compile it and load the class. However, it gives you only better performance if the step does not take much runtime compared to the method call overhead and if you execute each generated piece of code a lot, so the JIT will optimize it.

Computation with time limit

I'm trying to write a construct which allows me to run computations in a given time window. Something like:
def expensiveComputation(): Double = //... some intensive math
val result: Option[Double] = timeLimited( 45 ) { expensiveComputation() }
Here the timeLimited will run expensiveComputation with a timeout of 45 minutes. If it reaches the timeout it returns None, else it wrapped the result into Some.
I am looking for a solution which:
Is pretty cheap in performance and memory;
Will run the time-limited task in the current thread.
Any suggestion ?
EDIT
I understand my original problem has no solution. Say I can create a thread for the calculation (but I prefer not using a threadpool/executor/dispatcher). What's the fastest, safest and cleanest way to do it ?
Runs the given code block or throws an exception on timeout:
#throws(classOf[java.util.concurrent.TimeoutException])
def timedRun[F](timeout: Long)(f: => F): F = {
import java.util.concurrent.{Callable, FutureTask, TimeUnit}
val task = new FutureTask(new Callable[F]() {
def call() = f
})
new Thread(task).start()
task.get(timeout, TimeUnit.MILLISECONDS)
}
Only an idea: I am not so familiar with akka futures. But perhaps its possible to stick the future executing thread to the current thread and use akka futures with timeouts?
To the best of my knowledge, either you yield (the computation calls to some scheduler) or you use a thread, which gets manipulated from the "outside".
If you want to run the task in the current thread and if there should be no other threads involved, you would have to check whether the time limit is over inside of expensiveComputation. For example, if expensiveComputation is a loop, you could check for the time after each iteration.
If you are ok for the code of expensiveComputation to check Thread.interrupted() frequently, pretty easy. But I suppose you are not.
I don't think there is any solution that will work for arbitrary expensiveComputation code.
The question is what are you prepared to have as constraint on expensiveComputation.
You have the deprecated and quite unsafe Thead.stop(Throwable) too. If your code does not modify any object but those it created by itself, it might work.
I saw a pattern like this work well for time-limited tasks (Java code):
try {
setTimeout(45*60*1000); // 45 min in ms
while (not done) {
checkTimeout();
// do some stuff
// if the stuff can take long, again:
checkTimeout();
// do some more stuff
}
return Some(result);
}
catch (TimeoutException ex) {
return None;
}
The checkTimeout() function is cheap to call; you add it to code so that it is called reasonably often, but not too often. All it does is check current time against timer value set by setTimeout() plus the timeout value. If current time exceeds that value, checkTimeout() raises a TimeoutException.
I hope this logic can be reproduced in Scala, too.
For a generic solution (without having to go litter each of your expensiveComputations with checkTimeout() code) perhaps use Javassist.
http://www.csg.is.titech.ac.jp/~chiba/javassist/
You can then insert various checkTimeout() methods dynamically.
Here is the intro text on their website:
Javassist (Java Programming Assistant) makes Java bytecode manipulation simple. It is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level. If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. The whole API is designed with only the vocabulary of the Java language. You can even specify inserted bytecode in the form of source text; Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors.
Aspect Oriented Programming: Javassist can be a good tool for adding new methods into a class and for inserting before/after/around advice at the both caller and callee sides.
Reflection: One of applications of Javassist is runtime reflection; Javassist enables Java programs to use a metaobject that controls method calls on base-level objects. No specialized compiler or virtual machine are needed.
In the currentThread?? Phhhew...
Check after each step in computation
Well if your "expensive computation" can be broken up into multiple steps or has iterative logic you could capture the time when you start and then check periodically between your steps. This is by no means a generic solution but will work.
For a more generic solution you might make use of aspects or annotation processing, that automatically litters your code with these checks. If the "check" tells you that your time is up return None.
Ill ponder a solution in java quickly below using annotations and an annotation processor...
public abstract Answer{}
public class Some extends Answer {public Answer(double answer){answer=answer}Double answer = null;}
public class None extends Answer {}
//This is the method before annotation processing
#TimeLimit(45)
public Answer CalculateQuestionToAnswerOf42() {
double fairydust = Math.Pi * 1.618;
double moonshadowdrops = (222.21) ^5;
double thedevil == 222*3;
return new Answer(fairydust + moonshadowdrops + thedevil);
}
//After annotation processing
public Answer calculateQuestionToAnswerOf42() {
Date start = new Date() // added via annotation processing;
double fairydust = Math.Pi * 1.618;
if(checkTimeout(start, 45)) return None; // added via annotation processing;
double moonshadowdrops = (222.21) ^5;
if(checkTimeout(start, 45)) return None; // added via annotation processing;
double thedevil == 222*3;
if(checkTimeout(start, 45)) return None; // added via annotation processing;
return new Answer(fairydust + moonshadowdrops + thedevil);
}
If you're very seriously in need of this you could create a compiler plugin that inserts check blocks in loops and conditions. These check blocks can then check Thread.isInterrupted() and throw an Exception to escape.
You could possibly use an annotation, i.e. #interruptible, to mark the methods to enhance.

Categories