Java Forum / General / January 2006
Execute commands later
Will - 02 Jan 2006 12:56 GMT Is it possible in Java to do the following?
I would like to queue a list of java statements to run at a later time. For example queue System.out.println("command one") .... more code .... queue System.out.println("command two") ... more code .....
then later run the queued commands
VisionSet - 02 Jan 2006 13:11 GMT > Is it possible in Java to do the following? > [quoted text clipped - 6 lines] > > then later run the queued commands See: Java.util.Timer Java.util.TimerTask
-- Mike W
Will - 02 Jan 2006 13:15 GMT No, that is not what i am trying to do. I don't want to run the statements at a specified delay after. I am trying to just create a queue of commands. Which i can then choose to run at a later point in the programme by issuing a statement.
Andrew McDonagh - 02 Jan 2006 13:18 GMT > No, that is not what i am trying to do. > I don't want to run the statements at a specified delay after. > I am trying to just create a queue of commands. Which i can then choose > to run at a later point in the programme by issuing a statement. so use a queue of 'command objects'
google for it.
VisionSet - 02 Jan 2006 13:50 GMT > No, that is not what i am trying to do. > I don't want to run the statements at a specified delay after. > I am trying to just create a queue of commands. Which i can then choose > to run at a later point in the programme by issuing a statement. Why not just stick them all in a Runnable and call new Thread(myRunnable).start() when you want to run them?
-- Mike W
Ranganath Kini - 02 Jan 2006 14:31 GMT Please look at the new ThreadPoolExecutor class in JDK 1.5, it is a way to pool tasks and then execute them at a later time. For more information please have a look at:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html
Regards, Ranganath
Roedy Green - 03 Jan 2006 03:55 GMT > Which i can then choose >to run at a later point in the programme by issuing a statement. Presumably you can concoct some object that encapsulates the command with a interface with a method to execute it. Now see http://mindprod.com/jgloss/queue.html
You add to the queue to queue up work to do and you pop elements off the queue to do them.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Juhan Kundla - 02 Jan 2006 14:35 GMT Hei!
> Is it possible in Java to do the following? > [quoted text clipped - 6 lines] > > then later run the queued commands Use the command pattern and a Queue class. The following is (simplified example of) how i implemented the same thing for one of my projects.
public interface Command {
public void execute();
}
public class CommandOne implements Command {
public void execute() { System.out.println("command one") // .... more code .... }
}
// Etc, more implementations for the Command
import java.util.LinkedList; import java.util.Queue;
public class CommandRunner {
private Queue<Command> commands = new LinkedList<Command>();
public void executeCommands() { for (Command command; (command = commands.poll()) != null; ) { command.execute(); } }
public void queueCommand(Command command) { commands.offer(command); }
}
Will - 02 Jan 2006 15:52 GMT Thanks for the suggestions, but isn't there anything simpler?
Looking at a smaller sub problem.
If i have a string, is there any way to execute the string as a statement? For example if i have a string with the value "System.out.println("OUT")"
Is there any way to execute the strings content as a statement?
Ranganath Kini - 02 Jan 2006 16:28 GMT > Thanks for the suggestions, but isn't there anything simpler? > [quoted text clipped - 5 lines] > > Is there any way to execute the strings content as a statement? As far as I can say. There is no facility of this kind till now. Maybe we can look forward to Java compiler services within java applications. That wud allow us to execute Java statements from within our program.
For now, u eiether have to write ur own Java compiler (which is a mammoth task) or wait for Sun to bring in runtime compiler services.
Regards, Ranganath
Patrick May - 02 Jan 2006 16:57 GMT > Thanks for the suggestions, but isn't there anything simpler? > [quoted text clipped - 5 lines] > > Is there any way to execute the strings content as a statement? That's not currently possible in Java. It's straightforward in Common Lisp (among other languages), though. Do you have to use Java for your solution?
Regards,
Patrick
------------------------------------------------------------------------ S P Engineering, Inc. | The experts in large scale distributed OO | systems design and implementation. pjm@spe.com | (C++, Java, Common Lisp, Jini, CORBA, UML)
Will - 02 Jan 2006 17:02 GMT I do have to use Java.
I have found an alternative approach which is implementable in java.
Just thought that it seemed like such a simple idea.
Anyways, Never mind.
Thomas Hawtin - 02 Jan 2006 17:29 GMT >>Thanks for the suggestions, but isn't there anything simpler? >> [quoted text clipped - 9 lines] > Common Lisp (among other languages), though. Do you have to use Java > for your solution? You would probably try to avoid doing it in Lisp, wouldn't you?
More natural would be to use closures, which is more or less what anonymous inner classes are (although they are verbose).
You can compile Java from Java. javac is written in Java. Web app servers compile Java in JSPs without issue.
Tom Hawtin
 Signature Unemployed English Java programmer http://jroller.com/page/tackline/
Patrick May - 02 Jan 2006 17:50 GMT > > That's not currently possible in Java. It's straightforward > > in Common Lisp (among other languages), though. Do you have to > > use Java for your solution? > > You would probably try to avoid doing it in Lisp, wouldn't you? Yes, exec is a code smell.
> More natural would be to use closures, which is more or less what > anonymous inner classes are (although they are verbose). I'd say that closures are what anonymous inner classes dream about being when they grow up.
On further thought, it seems that the original poster really wants the equivalent of Scheme's continuations.
Regards,
Patrick
------------------------------------------------------------------------ S P Engineering, Inc. | The experts in large scale distributed OO | systems design and implementation. pjm@spe.com | (C++, Java, Common Lisp, Jini, CORBA, UML)
Chris Smith - 04 Jan 2006 04:22 GMT > I'd say that closures are what anonymous inner classes dream > about being when they grow up. I often wonder whether people say this because they really mean it, or because they don't like the syntax of anonymous inner classes. Aside from the ability to modify local variables, and dynamic typing stuff, what is lacking in anonymous inner classes that's present in a typical language implementing closures?
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Chris Uppal - 04 Jan 2006 11:50 GMT > > I'd say that closures are what anonymous inner classes dream > > about being when they grow up. [quoted text clipped - 4 lines] > what is lacking in anonymous inner classes that's present in a typical > language implementing closures? Fluidity of expression, principally. I.e. the biggest problem is the syntax -- but it's not /mere/ syntax, it's SYNTAX ! Without a good syntax (and -- of course -- the absence of stupid irregularities in the semantics) anonymous inner classes don't aproximate to closures because they can't feasibly be /used/ as closures.
An additional impoverishment of anonymous inner classes, at least when compared to Smalltalk "blocks"[*], is that there is no way for the "closure" code to return from the invoking method -- i.e. from the context of which it is logically part. It can only return from the concrete method defined against the inner class. That is a very severe limitation, possibly a show-stopper -- at least it would make impossible the kind of convenient /and/ flexible, but closure-heavy, APIs one finds in Smalltalk.
([*] which are how closures appear in that language -- and which are probably more relevant to Java than, say, closures as they appear in Lisp)
-- chris
Thomas Hawtin - 04 Jan 2006 18:11 GMT > An additional impoverishment of anonymous inner classes, at least when compared > to Smalltalk "blocks"[*], is that there is no way for the "closure" code to [quoted text clipped - 3 lines] > at least it would make impossible the kind of convenient /and/ flexible, but > closure-heavy, APIs one finds in Smalltalk. You're not into the Single Entry Single Exit style then?
Tom Hawtin
 Signature Unemployed English Java programmer http://jroller.com/page/tackline/
Chris Uppal - 05 Jan 2006 10:50 GMT > You're not into the Single Entry Single Exit style then? No! God forbid.
(Incidentally, if Java had true closures then presumably they should also be able to break out of loops, and so on, as well as returning from the enclosing method.)
-- chris
Thomas Hawtin - 05 Jan 2006 13:11 GMT >>You're not into the Single Entry Single Exit style then? > [quoted text clipped - 3 lines] > able to break out of loops, and so on, as well as returning from the enclosing > method.) You could always use exceptions. Though the syntax just gets worse and worse.
Tom Hawtin
 Signature Unemployed English Java programmer http://jroller.com/page/tackline/
castillo.bryan@gmail.com - 05 Jan 2006 13:46 GMT > > You're not into the Single Entry Single Exit style then? > [quoted text clipped - 3 lines] > able to break out of loops, and so on, as well as returning from the enclosing > method.) Can you explain why or give an example of why you would return from the enclosing method?
I know perl allows you to create closures and return the closure you just created, so something else can execute it later. I had used closures as callbacks to gui events in perl/Tk. It would seem strange to me that you would return from the enclosing method from the execution of a closure, when you are no longer even in the enclosing method.
> -- chris Chris Smith - 05 Jan 2006 16:03 GMT > Can you explain why or give an example of why you would return from the > enclosing method? Smalltalk, for example, implements loops in terms of blocks... so the reasons are the same as why you'd return from the body of a for loop.
> I know perl allows you to create closures and return the closure you > just created, so something else can execute it later. I had used > closures as callbacks to gui events in perl/Tk. It would seem strange > to me that you would return from the enclosing method from the > execution of a closure, when you are no longer even in the enclosing > method. Indeed, it does seem strange if you're doing things for which it doesn't make sense. In Java, anonymous inner classes are used almost exclusively for things where returnings from the enclosing context doesn't make sense.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Chris Uppal - 06 Jan 2006 09:51 GMT > Can you explain why or give an example of why you would return from the > enclosing method? [quoted text clipped - 5 lines] > execution of a closure, when you are no longer even in the enclosing > method. What I think you are missing is that in a language with proper support for closures, and where the APIs make good use of closures, the most common uses (by far) do not outlive the context that created them.
For instance, in Smalltalk, the normal Collections API includes a method called #at:ifAbsent: -- which takes two parameters, one is the key or index to look under in the container, the second is a zero-parameter block which will be evaluated if and only if there is no such key. A common pattern in Smalltalk code is for the caller to invoke #at:ifAbsent: to attempt to retrieve a value, passing a block which just causes the caller to return. Thus the method will "early-out" if there is no such key.
(Other patterns exist too, for instance there are Collections method #at:ifAbsentPut: and #at:ifPresent: which also take blocks. Indeed this kind of use of blocks is pervasive in Smalltalk-style APIs).
Smalltalk does not have the notion of breaking out of a loop, or of "continue"-ing a loop, but Java does, so in Java (if it had what I would call proper closures) it would be natural to be able to include "break" and "continue" statements in the code blocks too.
Note that the "closure" property of closures (that they "close over" the values of variables) is not important for these purposes. It is -- of course -- vital that the code snippets that form blocks be able to read and re-bind the values of variables in the enclosing scope(s), but that is more-or-less orthogonal to the property(ies) I'm talking about here.
-- chris
Stefan Ram - 06 Jan 2006 15:38 GMT >For instance, in Smalltalk, the normal Collections API includes a method called >#at:ifAbsent: -- which takes two parameters, one is the key or index to look [quoted text clipped - 3 lines] >passing a block which just causes the caller to return. Thus the method will >"early-out" if there is no such key. I have tried to imitate the Smalltalk Boolean types and Smalltalk blocks in Java.
I have implemented the following pseudocode in Java - not using Java's type "boolean" or "java.lang.Boolean" anywhere:
[ int i = 0; while( [ i < 3 ], [ int j = 0; print( i++, j++ )])]
See
http://purl.net/stefan_ram/pub/smalltalk-blocks-in-java
Chris Uppal - 08 Jan 2006 11:57 GMT > I have tried to imitate the Smalltalk Boolean types and > Smalltalk blocks in Java. [quoted text clipped - 7 lines] > > http://purl.net/stefan_ram/pub/smalltalk-blocks-in-java Hmm....
;-)
-- chris
P.Hill - 07 Jan 2006 05:43 GMT > A common pattern in Smalltalk > code is for the caller to invoke #at:ifAbsent: to attempt to retrieve a value, [quoted text clipped - 4 lines] > #at:ifAbsentPut: and #at:ifPresent: which also take blocks. Indeed this kind > of use of blocks is pervasive in Smalltalk-style APIs). Chris, these are very interesting examples because in Java (or C++ or C) the simplest code would take a different (but not necessarily better or worse) style and be separated into: do 1, then do 2. 1. go into the collection, returning a value which answers the question. 2. then act upon whichever path is coded (Absent, AbsentThusPut or Present)
The use-a-block style seems like it could be served in Java by a variation of a Visitor Pattern, where the collection finds the answer then uses the provided Visitor to act upon the absence or present. To get this same effect of a block executed later would require many more lines of inner-class with some reference to the enclosing the outer class. Hmm, for grins I think I should try that and see what it looks like. Now, this will be bugging me until I implement it. Thanks for the thought problem Chris! I'll let you know how it goes.
Maybe something that allows a user to provide what to do in the found and not found case. Maybe ...
myCollection.presentThus( item, new ThusBlock() { public void present() { doSomething(); } public void notPresent() { doSomethingElse(); } }
But I see how a purely functional language would find this a more useful construct.
I guess the next question becomes: Under what conditions in Smalltalk (and not lisp) is the equivalent of the following construct not actually the simplest thing to say just like it is in Java (and C++ etc.)?
if ( myCollection.isPresent() { doSomething(); }
-Paul
Chris Uppal - 08 Jan 2006 12:07 GMT > myCollection.presentThus( item, new ThusBlock() { > public void present() { [quoted text clipped - 4 lines] > } > } Yes, using more than one polymorphic method inside the "closure" is a good way to get the best millage out of the irreducably verbose syntax. BTW, you can also make the syntax work harder by putting some or all of the logic into the base class -- logic that might otherwise have to be duplicated in each Collection which accepted a ThusBlock.
> I guess the next question becomes: > Under what conditions in Smalltalk (and not lisp) is the equivalent of [quoted text clipped - 4 lines] > doSomething(); > } I would say that code like that is worse under /all/ conditions -- the problem is that you end up asking the same question twice. "Do you contain key X ?" and then "do something with key X". That kind of duplication is both complicating and inefficient[*]. It also reduces the extent to which the code /directly/ expresses the author's intent.
-- chris
([*] I wouldn't normally be too bothered about efficiency, but in this case we are talking about a pervasive idiom.)
Lasse Reichstein Nielsen - 05 Jan 2006 21:52 GMT > (Incidentally, if Java had true closures then presumably they should > also be able to break out of loops, and so on, as well as returning > from the enclosing method.) That sounds more like continuations than closures.
Closures are first class function values that include the binding of all their variables at the time of their creation (like the closure returned by this Javascript function: function twice(f) { return function(x){ return f(f(x)); }; } or this Scheme function (lambda(f)(lambda(x)(f(f x)))) or even this curried ML function fun twice f x = f (f x)
Reified continuations on the other hand, as you can do it in Scheme, is pure magic :) /L
 Signature Lasse Reichstein Nielsen - lrn@hotpop.com DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html> 'Faith without judgement merely degrades the spirit divine.'
Chris Uppal - 06 Jan 2006 09:51 GMT > > (Incidentally, if Java had true closures then presumably they should > > also be able to break out of loops, and so on, as well as returning > > from the enclosing method.) > > That sounds more like continuations than closures. Not to me. Continuations are a completely different beast.
> Closures are first class function values that include the binding of > all their variables at the time of their creation That's what "closure" means in contexts where there is nothing /but/ functions/expressions. The point I'm making is that in Java there are other "actions" available to code which are /not/ restricted to the evaluation of expressions (in an environment). Hence the proper generalisation of what-Lispers-call-closures would (or at least should) not correspond exactly to the Lisp concept.
Perhaps a better way of stating it is that what's needed is a way of creating code snippets that may not be executed immediately. In Smalltalk such things are called Blocks (or some similar name), and they are universally seen as the Smalltalk version of Lisp closures, but in fact they have richer semantics, because Smalltalk does not even attempt to be a pure functional language. To the extent that Lisp is pure functional (or to the extent that any given use of Lisp is pure), the notion of a "closure" precisely captures the notion of "postponed code snippet".
-- chris
Patrick May - 04 Jan 2006 19:52 GMT > > I'd say that closures are what anonymous inner classes dream > > about being when they grow up. [quoted text clipped - 4 lines] > stuff, what is lacking in anonymous inner classes that's present in > a typical language implementing closures? I really mean it. The fact that anonymous inner classes don't "close" over the lexical environment is a significant issue, as is the verbose, complex syntax. The expressiveness of Common Lisp and Scheme is one of the great strengths of those languages. Limiting functionality and making the syntax clunky effectively destroys the concept of a closure.
Regards,
Patrick
------------------------------------------------------------------------ S P Engineering, Inc. | The experts in large scale distributed OO | systems design and implementation. pjm@spe.com | (C++, Java, Common Lisp, Jini, CORBA, UML)
Luc The Perverse - 02 Jan 2006 20:10 GMT > Thanks for the suggestions, but isn't there anything simpler? > [quoted text clipped - 5 lines] > > Is there any way to execute the strings content as a statement? Um directly - and certainly not in a simpler fashion than what the other people are describing.
Why not just store the strings of what you want to print out later in an array and then call System.out.println at that time?
What are you trying to do? If there is some specific reason why the suggestions made thus far will not work, then it would be better if you could explain the reason, instead of dodging it. Likely, if we know what your problem is, we can suggest a better way to solve it. Even if there were some easy way of storing text java commands and then running them later, it is not going to be particularly efficient.
-- LTP
:) Will - 02 Jan 2006 20:44 GMT Like i say I have already solved my problem, but if you want to the reasoning behind my initial question, it is this:
I am using java to generate latex code. I call methods in another java class which in turn produce latex code. I was wishing to queue up a number of method calls and then execute them all at once, once a condition was true.
Thought there would be a simple way to do this, but alas no so I did it a different way.
Luke Meyers - 03 Jan 2006 08:06 GMT > I was wishing to queue up a > number of method calls and then execute them all at once, once a > condition was true. > > Thought there would be a simple way to do this, but alas no so I did it > a different way. I thought the suggestion you got to create a queue of Runnables was perfectly reasonable and straightforward. Or Callables, depending on your needs. Have a look at Executor and ExecutorService in java.util.concurrent. They are tailor-made to do exactly what you said you wanted. What was your less complex solution?
Luke
Ranganath Kini - 06 Jan 2006 04:49 GMT Looks like the Sun development team heard of your requirement and they have added a new feature in JDK 6 codenamed "Mustang" called - Java Compiler API.
The following link shud give u more information: http://jcp.org/en/jsr/detail?id=199
And here is an early draft of the Java Compiler API, download the file ( I guess u also need to download the latest binary build of JDK 6 to run the examples).
http://jcp.org/aboutJava/communityprocess/edr/jsr199/index.html
It carries an example of executing Java code off a string. Just as u wanted. ;-)
Hope this helps!
Best Regards, Ranganath Kini
Roedy Green - 03 Jan 2006 03:56 GMT >Is there any way to execute the strings content as a statement? you could compose a bat file and exec it later.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Luc The Perverse - 03 Jan 2006 05:19 GMT >>Is there any way to execute the strings content as a statement? > you could compose a bat file and exec it later. I see where you are going with this - but in this case I think it is best to try to prevent this person from doing whatever he is trying.
-- LTP
:) Roedy Green - 03 Jan 2006 22:44 GMT On Mon, 2 Jan 2006 22:19:20 -0700, "Luc The Perverse" <sll_noSpamlicious_z_XXX_m@cc.usu.edu> wrote, quoted or indirectly quoted someone who said :
>I see where you are going with this - but in this case I think it is best to >try to prevent this person from doing whatever he is trying. I think the problem is the current package sounds scary, even though it will end up just being page of code all told.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Alun Harford - 02 Jan 2006 19:24 GMT > Is it possible in Java to do the following? > [quoted text clipped - 6 lines] > > then later run the queued commands I guess you could do if you wanted. Read http://java.sun.com/docs/books/tutorial/reflect/object/invoke.html
Alun Harford
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|