Can anybody show an example of how to use heap.heapForEachClass in a select statement?
It would be great if you could provide some links with different examples of queries (other than those in the oqlhelp page of course :) )
I don't believe heap.forEachClass() is meant to be used in a select statement, at least not directly. Consider the fact that it doesn't return anything:
var result=heap.forEachClass(function(it){return it;});
typeof result
//returns undefined
The OQL used in jhat and VisualVM does support plain ol' JavaScript, just like the "query" I use above. I believe that the heap.forEachClass() finds more use in either JavaScript-style queries or in JavaScript functions within select-type queries.
That said, I don't know why this function exists since the heap.classes() enumeration is much easier to use, both with with select-style queries and plain JavaScript ones.
You could even even recreate the same functionality as heap.forEachClass() with the following JavaScript function:
function heapForEachClass(func){
map(heap.classes(),func)
return undefined;
}
Any sample queries that I could provide you would likely be easier written with heap.classes(). For example, you could use heap.forEachClass() to get list of all classes:
var list=[];
heap.forEachClass(function(it){
list.push(it);
});
list
but this is more complicated than how you'd do it with heap.classes():
select heap.classes()
or just
heap.classes()
I've used this function before to look for classes that are loaded multiple times (usually, this happens when two different class loaders load the same lib taking more memory for no reason, and making the JVM serialize and deserialize objects passed from one class instance to the other -because it doesn't know that they are actually the same class-)
This is my OQL script that selects (and count) classes that has the same name:
var classes = {};
var multipleLoadedClasses = {};
heap.forEachClass(function(it) {
if (classes[it.name] != null) {
if (multipleLoadedClasses[it.name] != null) {
multipleLoadedClasses[it.name] = multipleLoadedClasses[it.name] + 1;
} else {
multipleLoadedClasses[it.name] = 1;
}
} else {
classes[it.name] = it;
}
});
multipleLoadedClasses;
hopes that this will help further visitors ;)
Related
I've been playing around with the jdk.incubator.foreign stuff in JDK-18. It's pretty nice. WAY faster than JNI. An order of magnitude faster. The foreign memory stuff is better (and maybe slightly faster) than the UNSAFE stuff. Can't wait for this to ship.
One thing I can't figure out: How to upCall to a non-static JVM function?
If I can't, how do I pass some context down and back so I can cast the context into the correct instance/type in the java static function? In java how do you create a ValueLayout.ADDRESS from this? And vice-versa?
The only way I can figure out how to do it is to keep a list of instantiated classes, and round-trip the index in the list. Which seems like a hack.
Maybe the JVM reserves the right to move JVM memory around without restriction whenever it feels like it, so maybe it's not possible? If so, what is the recommended pattern for this?
--- edit - Add code example ---
public class RoundTripExample {
private String name;
RoundTripExample(String _name) {
this.name = _name;
}
public void callback() {
System.out.println("Called from native"+name);
}
public static void main(String[] args) throws Throwable {
var fName = new File("../zig/zig-out/lib/libnativeFuncs.so").getCanonicalFile();
System.load(fName.toString());
var instance =new RoundTripExample("round trip name");
CLinker link = CLinker.systemCLinker();
SymbolLookup symLook = SymbolLookup.loaderLookup();
ResourceScope scope = ResourceScope.newSharedScope();
var nativeFunc = link.downcallHandle(
symLook.lookup("zigCallTest").get(),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS)
);
var handle =
MethodHandles.lookup().findVirtual(
RoundTripExample.class,
"callback",
MethodType.methodType(void.class)
);
handle.bindTo(instance);
var upcall = link.upcallStub(
handle,
FunctionDescriptor.ofVoid(ValueLayout.ADDRESS),
ZigStubs.scope
);
nativeFunc.invoke(upcall);
}
}
Assuming this is the way to do it, the problem is creating the upCall handle. You can only pass it a handle to functions that take LONG, INT, ADDRESS, etc. An instance of a class isn't any of those.
If the context you need to pass is constant for the target function, you could bind it to the target method handle using MethodHandles.insertArguments and then use the resulting method handle to create an upcall stub.
If the context is not constant for the target function, then your idea of using a list and passing around the index to the object you want is a pretty good way to go. This is essentially a way to turn an object into an integer, by inserting it into the list, and then back into an object by looking it up in the list again.
There's no safe way of turning an object into a plain native address, since, as you say, the object might be move by the JVM.
In the example, using bindTo looks feasible. In this case you've forgotten to assign the result of bindTo:
handle = handle.bindTo(instance);
Additionally, you'd have to drop the address argument passed from native code, as it looks like it's not being used by your Java code:
handle = MethodHandles.dropArguments(handle, 0, MemoryAddress.class);
var upcall = link.upcallStub(
handle,
FunctionDescriptor.ofVoid(ValueLayout.ADDRESS),
ZigStubs.scope
);
I am trying to get a grasp on Google App Engine programming and wonder what the difference between these two methods is - if there even is a practical difference.
Method A)
public Collection<Conference> getConferencesToAttend(Profile profile)
{
List<String> keyStringsToAttend = profile.getConferenceKeysToAttend();
List<Conference> conferences = new ArrayList<Conference>();
for(String conferenceString : keyStringsToAttend)
{
conferences.add(ofy().load().key(Key.create(Conference.class,conferenceString)).now());
}
return conferences;
}
Method B)
public Collection<Conference> getConferencesToAttend(Profile profile)
List<String> keyStringsToAttend = profile.getConferenceKeysToAttend();
List<Key<Conference>> keysToAttend = new ArrayList<>();
for (String keyString : keyStringsToAttend) {
keysToAttend.add(Key.<Conference>create(keyString));
}
return ofy().load().keys(keysToAttend).values();
}
the "conferenceKeysToAttend" list is guaranteed to only have unique Conferences - does it even matter then which of the two alternatives I choose? And if so, why?
Method A loads entities one by one while method B does a bulk load, which is cheaper, since you're making just 1 network roundtrip to Google's datacenter. You can observe this by measuring time taken by both methods while loading a bunch of keys multiple times.
While doing a bulk load, you need to be cautious about loaded entities, if datastore operation throws exception. Operation might succeed even when some of the entities are not loaded.
The answer depends on the size of the list. If we are talking about hundreds or more, you should not make a single batch. I couldn't find documentation what is the limit, but there is a limit. If it not that much, definitely go with loading one by one. But, you should make the calls asynchronous by not using the now function:
List<<Key<Conference>> conferences = new ArrayList<Key<Conference>>();
conferences.add(ofy().load().key(Key.create(Conference.class,conferenceString));
And when you need the actual data:
for (Key<Conference> keyConference : conferences ) {
Conference c = keyConference.get();
......
}
In my project I'm using Neo4j's Core-API through GraphDatabaseService. In Tests we have an EmbeddedGraphDatabase where everything works as expected. I then wrote some tests to see how my implementation behaves on a RestGraphDatabase, just to find out, that most of it fails!
(The GraphDatabaseService is obtained by GraphDatabaseFactory of the Rest-API, so without an instanceof check I do not know which one it is)
Some examples:
If I use GlobalGraphOperations everything will fail, because GlopalGraphOperations are not supported by the RestGraphDatabase. (Strange enough that GlobalGraphOperations.at doesn't throw but all methods from GlobalGraphOperations).
Then I thought "ok I'll use Cypher to get the same behavior."
I tryed to implement a Method like this:
public getNodesWithLabel(String label, GraphDatabaseService graphService){
try(Transaction tx graphService.beginTx()){
ExecutionEngine ee = new ExecutionEngine(graphService);
//throws NullPOinterExeption in execute method
ExecutionResult result = ee.execute("MATCH (n:" + label + ") RETURN n");
result.columnAs("n");
//... mapping of Nodes
}
}
Searching through the API I see, that there is a RestCypherQueryEngine which is initialized via a RestAPIFascade. Problem here is, that the methods are not interchangeable, do not implement the same interface, and the return types are completeley different (i.e. ExecutionResult vs QueryResult)
So my question is: Is there a way, to get the same behavior from Neo4j where the used technology (Rest vs. Embedded) doesn't matter? Some kind of a technology independed Wrapper will suit my needs.
by the way, I'm using Neo4j in Version 2
Just don't do it. What it would do (if it worked) would be to execute every call to the database over the wire, ever read and write of nodes, rels and properties. You don't want to do that.
Use this instead.
queryEngine = new RestCypherQueryEngine(restGraphDb.getRestAPI());
queryEngine.query(query, params)
This sends the queries to the server and runs them there.
I am generating JavaScript code using velocity in java.
For example: I generated JavaScript and got below string:
importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{ return true;}}
Is there any java API that takes this String and formats this JavaScript in below manner:
importClass(java.util.ArrayList);
function fun(arg) {
if (true){
return true;
}
else{
return true;
}
}
Closure Compiler
You can use Google's Closure Compiler.
It formats, compresses, optimizes, and looks for mistakes in JavaScript code.
For a quick look what it can do, you can try the web service.
Example
For your example string,
importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{ return true;}}
if you just want to format it, use the compile options "Whitespace only" and "Pretty print", which returns:
importClass(java.util.ArrayList);
function fun(arg) {
if(true) {
return true
}else {
return true
}
}
;
Anyway, with Closure compiler, you have several options to optimize and/or format your input code (either given as string or file URI) and to either return the optimized/formatted JS as string or save it to a file.
I can really recommend to use the "Simple" optimization mode. For longer Javascripts, it really saves you lots of unneeded bytes. Plus, it speeds up script execution!
For your example string, compile options "Simple" (instead of "Whitespace only") and "Pretty print" return
importClass(java.util.ArrayList);
function fun() {
return!0
}
;
As you can see, the result of both fun() functions is the same (Boolean true).
However, the second has removed all useless code (by remaining validity!) and will be executed faster.
Download & Reference
Now, the actual compiler is written in Java and is available as a command-line utility to download (Update 2014-07-10: New Downloadlink).
As a second option, you could implement your own wrapper class to communicate with the REST API (as I did for PHP). Doesn't require too much effort/code.
More info is available here:
Google Code Project Page
Getting Started
FAQ: How do I call Closure Compiler from the Java API?
REST API Reference
Hope that helps.
I am working on a Java program where an object needs to have user-customization behavior for one function. I am implementing this using Mozilla Rhino, JavaScript and Java.
I cannot figure out how to take the already instantiated object and pass it to a pre-written script.
I have looked through many tutorials on Rhino, and none have given an example like this. Any advice or links would be greatly appreciated.
Thank you for your time.
This answer to another question passes an object, data, from Java to Rhino Javascript.
I have no idea whether or not it works (well I suppose it does). Here are the relevant parts:
public static class data {
Double value = 1.0d;
}
ScriptEngine engine = new ScriptEngineManager().getEngineByName ("rhino");
data data = new data();
Context.enter().getWrapFactory().setJavaPrimitiveWrap(false);
engine.eval("function test(data) { return data.get('value1') + 5;};");
System.out.println("Result:" + ((Invocable)engine).invokeFunction("test", data));
(I didn't know about that setJavaPrimitiveWrap(), here is some WrapFactory Javadoc.)