суббота, 18 февраля 2017 г.

Java 8: Integer

Everyone knows that Java has boxing functionality:
 Integer one = 4;
 Integer two = 4;
 Assert.assertTrue(one==two);

 Integer $600 = 600;
 Integer also600 = 600;
 Assert.assertTrue($600 != also600);


It works as written in JLS (http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.7).
This is due to the caching functionality inside the Integer class and the method Integer.valueOf which is used by boxing.

What's more we can make the second test pass. Cache inside Integer can be tuned by passing  system property -Djava.lang.Integer.IntegerCache.high=600 to the JVM. The bad thing is that low bound of Integer cache cannot be tuned.

Another example is:
 Integer $4 = new Integer(4);
 Integer $anotherInstance = 4;
 Assert.assertTrue($anotherInstance!=$4);

This is because new Integer(4) bypasses the cache.  Why? Is it a good design?
Is it the premature optimization evil?
Interesting case that other wrapper classes also contain the caching functionality, but only Integer class has the possibility to tune the size of the cache.

One more thing: do we actually need Integer constructor which accepts String if the same goal can be achieved with Integer.valueOf method?

вторник, 14 февраля 2017 г.

Java StringBuilder and StringBuffer

As to know more about the implementation of the JVM I started to look at the java source code. StringBuilder and StringBuffer are two pretty often used classes.
Documentation says that it is recommended to use StringBuilder class as it will be faster under most implementations. But.. documentation does not say about possible performance gains.
I wrote a quick check for appending String and char for both classes.
For the tests I used Oracle JDK 1.8.0b51.  Here is the sample code:
    @Test
    public void stringBufferTest(){
        Eap.execute(()->{
            StringBuffer stringBuffer = new StringBuffer();
            String a = "a";
            for (int i = 0; i< $256_MEGABYTES; i++){
                stringBuffer.append(a);
            }
        });
    }
    @Test
    public void stringBuilderTest(){
        Eap.execute(()->{
            StringBuilder stringBuilder = new StringBuilder();
            String b = "b";
            for (int i = 0; i< $256_MEGABYTES; i++){
                stringBuilder.append(b);
            }

        });
    }

And results:
Time is: 9,105000 seconds
Time is: 3,220000 seconds

Absolute numbers tell nothing, so StringBuilder is almost 2.8 faster then StringBuffer. 

For chars I just substitute String a = "a" to char a = 'a' and String b = "b" to char b = 'b'.

In case of char appending we get following results:
Time is: 8,623000 seconds
Time is: 1,221000 seconds
So StringBuilder is almost 7 times faster then StringBuffer. 

Although these results were obtained on relatively long strings it is much more clear now which class to use in your application (depending on the requirements of course). Interesting fact is that both StringBuffer and StringBuilder extend from AbstractStringBuilder.

A couple of questions to the internal design of these classes:
1) both of them expose internal capacity, which is 16 by default. Why it is 16? What is this magic number for?
2) Overloaded constructors with different semantics. So, one constructor accepts capacity and another one accepts string.
3) Both classes provide methods capacity() and length(). Both of them return data. Why didn't they call them with get prefix like getCapacity() and getLength()?

воскресенье, 12 февраля 2017 г.

Validate XML by XSD with includes from classpath

Validation of XML files is usually a standard task.
It is very convenient to store XSDs in classpath and validate XML in a such way.
Problems starts when XSD contains imports of other schemas. Schema parser doesn't know how to resolve the location of imports. There is no out of box solution to this problem.

I created a sample project that solves this task: 
https://github.com/chernykhalexander/xsdValidator

среда, 25 января 2017 г.

Java 8. Execute Around Method pattern.

After reading Venkat Subramaniam book on Java 8 I was impressed with Execute Around Method pattern.
Execute Around Method pattern is useful when the pre- and post-operations have to be guaranteed and the usage of the instance has to be rather narrow and enforced.
Here is the example:
package ru.chernykh.java8;

import java.util.function.Consumer;
public class UsefulResource {
    private UsefulResource() {
        System.out.println("Instantiate resource");
    }
    private void close() {
        System.out.println("close resource");
    }
    public void operator(){
        System.out.println("execute logic");
    }
    public static void process(Consumer<UsefulResource> block) {
        UsefulResource usefulResource = new UsefulResource();
        try {
            block.accept(usefulResource);
        } finally {
            usefulResource.close();
        }
    }

    public static void main(String[] args) {
        UsefulResource.process(usefulResource -> {
            usefulResource.operator();
        });
    }
}


And the output is:
Instantiate resource
execute logic
close resource


Also, more information can be found in his publication at http://www.oracle.com/technetwork/articles/java/architect-10things-2266262.html.

четверг, 22 декабря 2016 г.

Maven Enforcer Plugin

Due to continuous integration sometimes it is difficult to control build environment. Someone can wrongly setup Jenkins job and your project won't build. In order to identify such errors much more faster one can use maven-enforcer-plugin. Just add the following xml to the pom and that's it:

                <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>${maven.enforcer.plugin.version}</version>
                <executions>
                    <execution>
                        <id>enforce-versions</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <requireMavenVersion>
                                    <!--
                                      Maven 3.0.3 or later. That's the earliest version to enforce
                                      declaration ordering for plugins in the same phase.
                                     -->
                                    <version>[3.0.3,)</version>
                                </requireMavenVersion>
                                <requireJavaVersion>
                                    <!-- Java 1.8 or later. -->
                                    <version>[${java.version},)</version>
                                </requireJavaVersion>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

Java Jackson 2. Custom Date deserialization in JSON.

Hi. I want to share receipt with you how to write custom date deserializator for Jackson 2. This could be helpful when you deserialize value into generic Map and want that dates actually were stored like java.util.Date not String.

Deserialization usually done like so:
 Map<String,Object> data = null;
 data = mapper.readValue(someInputStream,Map.class);


In order to create custom serializator one needs to extend the class com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer. Here is the example of custom date deserializator:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DDeserializer extends UntypedObjectDeserializer
   
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {

        if (jp.getCurrentTokenId() == JsonTokenId.ID_STRING) {
            try {
                LocalDate localDate = LocalDate.parse(jp.getText(),formatter);
                java.util.Date date = java.sql.Date.valueOf(localDate);
                return date;
            } catch (Exception e) {
                return super.deserialize(jp, ctxt);
            }
        } else {
            return super.deserialize(jp, ctxt);
        }
    }

    public static ObjectMapper regObjectMapper(ObjectMapper mapper){
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addDeserializer(Object.class, new DDeserializer());
        mapper.registerModule(simpleModule);
        return mapper;
    }
}

Please note, that here is java 8 Date & Time API is mixed with plain old Date API. But the approach here is important.
Take a note in regObjectMapper method. In order to use custom deserializator it needs to be registered in ObjectMapper. After this you could use it to deserealize strings in to Date.

понедельник, 20 июня 2016 г.

The Pragmatic Programmer: From Journeyman to Master.

Hello, my dear reader!

Today I'm going to provide some thoughts after reading the Pragmatic Programmer book.
Here are the thoughts that caught me:
  1. Tag a commit, to see how many number of files affected by the bug fix.
  2. Find the opportunity to refine the code.
  3. Flexible, adaptable design.
  4. Deployment: stand-alone, client-server, n-tier model just by changing a configuration file.
  5. Domain specific language.
  6. Know your shell & text editor.
  7. Fix the problem, not the Blame.
  8. Bertrand Meyer.
  9. Design by contract for java.
  10. Perl for text processing.
  11. Pluggable exception handlers.
  12. Resources: memory, transactions, threads, files, timers, sockets.
  13. Metaprogramming.
  14. Large-Scale C++ Software design.
  15. The project needs at least two "heads" -- one technical, the other administrative. The technical head sets the development philosophy & style, assigns responsibilities to teams, and arbitrates the inevitable "discussions" between people. The technical head also looks constantly at the big picture, trying to find any unnecessary commonality between teams that could reduce the orthogonality of the overall effort. The administrative head, or project manager, schedules the resources that the teams need, monitors and reports on progress, and helps decide priorities in terms of business needs. The administrative head might also act as the team's ambassador when communication with the outside world.
  16. Tool builders -> Automation of project activities.
  17. Give each member the ability to shine in his or her own way.
  18. Unit testing: resource exhaustion, errors, and recovery.
  19. Surviving Object-Oriented Projects: A Manager's Guide: Alister Cockburn.
  20. Eiffel.
  21. Michael Holt. Math puzzles & games.
 Nice book. Keep up!

суббота, 11 июня 2016 г.

My reading list. What has been done

Here is the first attempt to present you my reading list - what I had read already.
There are knowledge that expire too fast and knowledge that have more long term value.  Here I want to share the list of books that I think should be read by every developer.

This is not a complete list. I'm working on it. If only I knew that all these books existed when I was studying at the institute...
  1. Code Complete: A Practical Handbook of Software Construction, Second Edition 2nd Edition by Steve McConnell
  2. Effective Programming - More Than Writing Code - Jeff Atwood
  3. Soft Skills: The software developer's life manual 1st Edition by John Sonmez
  4. How to Stop Sucking and Be Awesome Instead by Jeff Atwood
  5. Joel on Software: And on Diverse and Occasionally Related Matters That Will Prove of Interest to Software Developers, Designers, and Managers, and to Those Who, Whether by Good Fortune or Ill Luck, Work with Them in Some Capacity by Joel Spolsky
  6. More Joel on Software: Further Thoughts on Diverse and Occasionally Related Matters That Will Prove of Interest to Software Developers, Designers, ... or Ill Luck, Work with Them in Some Capacity 2008th Edition by Avram Joel Spolsky
  7. Getting Started as an Independent Computer Consultant by Mitch Paioff
  8. The Deadline: A Novel about Project Management by Tom DeMarco 
  9. Design Patterns: Elements of Reusable Object-Oriented Software 1st Edition by Erich Gamma

If anyone wants to add something, feel free ;-)

суббота, 9 апреля 2016 г.

SQL and MongoDB

It has been a long time since I had used MongoDB. In the meantime I am very interested in the possibility to use plain SQL when working with MongoDB.

At first my toolbelt has the https://robomongo.org/ tool. This tool allow to ease the work with Mongo console. How can use SQL? That's the main question. There is a project Apache Drill which allows you to connect to MongoDB, Hadoop, Hbase, files and query with SQL. Moreover, you can use the Apache Drill jdbc driver with any tools that support JDBC!
Pretty good!