From java doc 1.8, seems Condition only has await(), await(long, TimeUnit), awaitNanos(), etc.
It doesn't have a function that looks like Condition.await(()->xxxxx) to wait until a condition is met. c++11 condition_variable supports to have cv.wait(mutex, predicate_function) so we can use a lambda function as a parameter to control when condition_variable should return from wait/await.
Does java support this?
From the docs, the C++ condition_variable::wait overload is just checking the predicate when a notification comes through and is equivalent to
while (!stop_waiting()) {
wait(lock);
}
So we can simply do the same thing in Java.
while (!someCondition()) {
conditionVariable.await();
}
Related
I have a dynamic template in which I use the special value {dynamic_type}, as I need it to work on every type that doesn't match any of my other templates. (https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-templates.html#template-variables)
My template is something along these lines (simplified from the real deal):
{
"default-mapping": {
"match_mapping_type":"*",
"mapping": {
"type": "{dynamic_type}",
"copy_to": "__general_search"
}
}
}
ElasticSearch has moved to a new Java API Client and I want to migrate my code. (https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/introduction.html)
The old Java API was very weakly typed and you could specify basically anything you wanted, but in the new api you have to use specific builders/methods, which are different for each type. So for a text field you'd do something like new Property.Builder().text(t -> t.copyTo("xyz")), for a boolean new Property.Builder().boolean_(b -> b.copyTo("xyz")), etc.
My question is, how do I now specify the dynamic type ({dynamic_type})? I can find no corresponding method/builder.
Update: I'm fairly certain this is bug/missing feature and have raised an issue for it at https://github.com/elastic/elasticsearch-java/issues/142
It has been fixed and backported to 7.17 it seems.
See also:
https://github.com/elastic/elasticsearch-java/issues/142#issuecomment-1136153730
I've implemented code in Scala that is using a method written in Java.
In the code below processSale() is a Java method that takes util.List<Sale> as a parameter.
I've converted Scala Iterable[Sale] to Seq[Sale] and then to util.List<Sale> with the help of scala.collection.JavaConverters._
val parseSales: RDD[(String, Sale)] = rawSales
.map(sale => sale.Id -> sale)
.groupByKey()
.mapValues(a => SaleParser.processSale(a.toSeq.asJava))
However when the code gets executed as part of a Spark driver the job fails due to the task failure with UnsupportedOperationException. I've looked through the logs and it appears that the reason is within the Java processSale method on the call of Collections.sort
Collections.sort(sales, new Comparator<InvocaCall>() {
#Override
public int compare(Sale sale1, Sale sale2) {
return Long.compare(sale1.timestamp, sale2.timestamp);
}
});
I'm stuck at this point because I'm passing the required util.List<Sale>. Why could Collections.sort be an unsupported operation in this case?
From this documentation:
Because Java does not distinguish between mutable and immutable
collections in their type, a conversion from, say,
scala.immutable.List will yield a java.util.List, where all
mutation operations throw an UnsupportedOperationException
toSeq from your code returns immutable.Seq, that's why you get the exception.
So you can convert your list to mutable data structure like ListBuffer:
list.to[scala.collection.mutable.ListBuffer].asJava
Add null check for rawSales util.List<Sale>.
val parseSales: RDD[(String, Sale)] = if (rawSales.nonEmpty)
//rawSales specific stream operations
else
//None or any code as per requirement
I'm learn rxjava using this article: http://blog.danlew.net/2014/09/22/grokking-rxjava-part-2/
and can't reproduce first example of this article
I did next:
Observable<List<String>> query(String text); //Gradle: error: missing method body, or declare abstract
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
query.subscribe(urls -> { //Gradle: error: cannot find symbol variable query
for (String url : urls) {
System.out.println(url);
}
});
}
But I have an errors, which I added as comments
What I did wrong?
Java 8 lambdas aside, most of the people here are missing the fact that your code won't compile regardless RetroLambda or any other nifty tool that you find somewhere to work around the missed lambda feature in Android...
So, take a close look to your code, you even had added some comments to the snippet which are actually explaining you why you are having some compilation errors:
1 You have a method with an empty body:
Observable<List<String>> query(String text);
So, add a method body to it and problem solved. What do you want to do? You don't know yet? Then add a dummy or empty body and work that out later:
Observable<List<String>> query(String text) {
return Observable.just(Arrays.asList("url1", "url2"));
}
2 There is no query variable at all in your code. What you've got is a query method, and the syntax to use methods requires you to use braces:
query("whatever").subscribe(urls -> {
for (String url : urls) {
System.out.println(url);
}
});
Now add the RetroLambda or use anonymous classes and you are done. Bear in mind that nothing out of this will add much functionality to your code but will solve just those compilation errors. Now ask yourself what do you want to do in your query method and carry on.
Note: An Observable object is a stream of data, which basically means that you might get zero elements, one element, or many; all of them instances of the specified type. So your code seems to expect a stream of lists of strings, if what you really want is a stream of strings, then replace Observable<List<String>> for Observable<String>.
By Gradle: error: you mean compilation error? You should probably put parentheses between query and .subscribe(urls -> { as this is not a variable or class filed but method instead, so you should call it to get Observable to subscribe to.
Well, also you need to implement query method to return Observable, for example like this:
private Observable<String> query() {
return Observable.just("one", "two", "three");
}
You'll get another build error because of Java 8 but as already mentioned in comments you can easily use retrolamda with gradle to fix the problem. Otherwise you can use Android Studio quick fixes to convert java 8 lambdas into java 6 anonymous classes.
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.
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 ;)