I am creating a new Netty pipeline and I am trying to:
avoid premature optimization.
write code that is easy to explain to one of my interns.
This sort of factory method is certainly easy to explain:
public String toJSON()
{
Gson gson = new Gson();
return gson.toJson(this);
}
In a somewhat related question, the OP asks if it is OK (meaning thread-safe) to re-use a single instance of a Gson object. My question is slightly different: is there a good reason to share the object? If so, at what level of complexity is it worth sharing the Gson object? Where is the trade-off?
It’s expensive, and the cost scales with the complexity of the data models you're using Gson to bind. I wrote a post, Reflection Machines, that explains why creating Gson instances is expensive and should be minimized.
Related
I'm new to Quarkus and I'm analysing the migration viability of a quite complex "Spring Boot" application.
One of the biggest challenges we have is regarding database access, which is performed with tons of native queries using "JdbcTemplate" like the example below:
return getJdbcTemplate().query( sql, rs -> {
Map< String, String > result = new HashMap<>();
while ( rs.next() ) {
result.put( rs.getString( "COLUMN_1" ), rs.getString( "COLUMN_2" ) );
}
return result;
} );
Sometimes the result is cast to a basic class (like "String.class"), but the absolute majority of cases the result is generated by a "ResultSetExtractor".
After some research I found indications that Panache accepts native query execution (as described here) and, following this post, I found this one with a very nice alternative using "entityManager.createNativeQuery()".
For the sake of simplicity (and my sanity), I've decided to use the "entityManager.createNativeQuery()" approach, converting the implemented "ResultSetExtractor" into "ResultTranformers", given that this won't demand, among other things, the "entitization" of some POJOs that are used on data retrieval by now.
The main objective at the end of this compatibility change is to have an application that can be executed on "Spring-boot" and "Quarkus" (at least regarding the persistence layer).
One question I have is regarding the "entityManager" declaration below:
#PersistenceContext
private EntityManager entityManager;
Considering that we will use, at this first moment, the "quarkus-spring-di" compatibility extension (which means the class that holds the "entityManager" is annotated with "#Repository" and not with "#ApplicationScoped"), the "entityManager" will be initialized?
And, considering all that was presented here, do you guys have any suggestions or warnings about the decided course of action?
Thanks and best regards!
I have a legacy springMvc project and i want to refactor all the controllers to return ResponseEntity object rather then returning Model object which is returned by default.
I am looking for a way to map functions in Map class to ResponseEntity class .
I have seen people recommend to use Regular expression as a solution to refactor all the methods.
I need to know your opinion about implementing Regex as solution in terms of advantages / drawbacks for using regex in this scenario.
In addition it would be helpful if you can suggest other solutions.
please take a look at the attached code for more details.
return Model object to the view
#GetMapping("/getData")
public String getData(Model model) {
model.addAttribute("message", "springMvc");
return "viewPage";
}
return ResponseEntity object as a json format
#GetMapping("/getData")
public ResponseEntity<Map<String,String>> getData() {
Map<String,String> map = new HashMap<>();
map.put("message", "springMvc");
return new ResponseEntity.Ok().body(map);
}
In case this problem is faced by someone in the future i would like to share that I have found a convenient way to do the refactoring of the code by using AST (Abstract Syntax Tree) which gives you a lot more control over the code comparing to using Regex.
you can check the library repository :
https://github.com/javaparser/javaparser
Note that AST is used by IDEs and Static analysis tools such as SonarQube
Regex cannot be used in your context. There are certainly too many special cases to change, it is not just a question of changing a string. JavaParser is a good candidate.
We were discussing with the colleagues as to why the call below returns an array in the ResponseEntity:
ResponseEntity<WakeupProviderSettingsDTO[]> rep =
restTemplate.getForEntity(url, WakeupProviderSettingsDTO[].class);
instead of a List<WakeupProviderSettingsDTO> or sth.
Why can't we simply transfer entities as lists?
Is it because There are no Class literals for parameterized types?
Is it a performance thing? is it because of the fixed size of response set?
As you have pointed out in that post.
You can not use .class token with parameterized types
This is one of those rare scenarios where you would use generic type List. So you could do like this
ResponseEntity<List> rep = restTemplate.getForEntity(url, List.class);
But with this you ofcourse lose the advantages that you would get with parameterized types.
If you wish to use List with parameterized types, You can still do it using ParameterizedTypeReference.
To answer your question, this has nothing to do with performance or fixet size response, this is a limitation of java Generics.
I am working on using a real time application in java, I have a data structure that looks like this.
HashMap<Integer, Object> myMap;
now this works really well for storing the data that I need but it kills me on getting data out. The underlying problems that I run into is that if i call
Collection<Object> myObjects = myMap.values();
Iterator<object> it = myObjects.iterator();
while(it.hasNext(){ object o = it.next(); }
I declare the iterator and collection as variable in my class, and assign them each iteration, but iterating over the collection is very slow. This is a real time application so need to iterate at least 25x per second.
Looking at the profiler I see that there is a new instance of the iterator being created every update.
I was thinking of two ways of possibly changing the hashmap to possibly fix my problems.
1. cache the iterator somehow although i'm not sure if that's possible.
2. possibly changing the return type of hashmap.values() to return a list instead of a collection
3. use a different data structure but I don't know what I could use.
If this is still open use Google Guava collections. They have things like multiMap for the structures you are defining. Ok, these might not be an exact replacement, but close:
From the website here: https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained
Every experienced Java programmer has, at one point or another, implemented a Map> or Map>, and dealt with the awkwardness of that structure. For example, Map> is a typical way to represent an unlabeled directed graph. Guava's Multimap framework makes it easy to handle a mapping from keys to multiple values. A Multimap is a general way to associate keys with arbitrarily many values.
We have a class that is more like a template (with lot of properties and overridden methods). I need to make many objects of that class type. Can I use clone() to create objects with specific settings if I have one object created? I know I need to override the Clone method. Is the performance going to take a hit by using Clone()?
Cloning an object as a way of creating new objects is not necessarily the cleanest method of creating objects. It is better to use constructors or factory methods (which call constructors).
You may be interested in using a factory or builder pattern. Or if you are worried about the memory overhead of a large number of similar objects, take a look at the flyweight pattern.
Clone in itself is not bad practice, its generally shallow. BUt i think you want to be using a pattern. More than likely Prototype Pattern is your solution.
The clone you are doing is really a cookie cutting of your prototype.
The link i sent is from DO factory and has code samples for you.