Tuesday, October 4, 2016

Java Misc Part 3



http://massivetechinterview.blogspot.com/2017/12/java-misc-part-4.html
https://martinfowler.com/bliki/EncapsulatedCollection.html

https://dzone.com/articles/java-holiday-calendar-2016-day-25-the-complete-dec

https://dzone.com/articles/java-holiday-calendar-2016-day-8-use-traits-in-java
https://dzone.com/articles/java-holiday-calendar-day-9-event-sourcing
https://dzone.com/articles/java-holiday-calendar-2016-day-10-mapstream
https://dzone.com/articles/java-holiday-calendar-2016-day-19-speed-up-your-en

https://dzone.com/articles/java-holiday-calendar-2016-day-16-hacking-the-exis
The JVM has a command line parameter named "-Xbootclasspath/p:" that can be used to load Java classes before the standard java classes are loaded. This way, we can inject our own versions of Java classes before the real ones load.
This is also useful for other classes that are not a part of the standard Java library. If there is a bug in a third-party product, we can correct the bug and just load the correct version before the app loads. It also enables us to instrument classes so they, for example, can collect usage statistics or introduce or prevent certain things from happening.
public Integer(int value) {
    this.value = value;
    INSTANCE_CREATE_COUNTER.incrementAndGet();
}
Finally, add the following method:
@Override
protected void finalize() throws Throwable {
    INSTANCE_FINALIZE_COUNTER.incrementAndGet();
}

https://dzone.com/articles/using-traits-in-java-8
interface HasName extends Document {
    final String NAME = "name";
    default String getName() {
        return get(NAME);
    }
    default void setName(String name) {
        put(NAME, name);
    }
}
https://dzone.com/articles/java-holiday-calendar-2016-day-12-avoid-overloadin
Avoid Overloading With Lambdas
Today's tip is to think twice about the names you assign to you methods that can receive lambdas — and avoid letting them share the same name.
If there are two or more methods with the same name that take functional interfaces as parameters, then this would likely create a lambda ambiguity on the client side. For example, if there are two Point methods, add(Function<Point, String> renderer) and add(Predicate<Point> logCondition), and we try to call point.add(p -> p + “lambda”) from the client code, the compiler is unable to determine which method to use and will produce an error. Instead, consider naming methods according to their specific use.

public interface Point {
    addRenderer(Function<Point, String> renderer);
    addLogCondition(Predicate<Point> logCondition);
}
https://dzone.com/articles/java-holiday-calendar-2016-day-14-submitting-a-tas
we need to shut down the custom thread pools we are creating, or else our program will not terminate properly (because there are still live threads hanging around). Closing a thread pool can be done like this:
try {
     forkJoinPool.shutdown();
     forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException ie) {
     ie.printStackTrace();
}

        // Runs in the main thread 
        helloWorld();
        // Runs in a new thread
        new Thread(Main::helloWorld).start();
        // Runs in the default fork join pool
        ForkJoinPool.commonPool().submit(Main::helloWorld);
        // Runs in the default fork join pool via a CompletableFuture
        CompletableFuture.runAsync(Main::helloWorld);
        // Runs in a custom fork join pool (with three workers)
        new ForkJoinPool(3).submit(Main::helloWorld)
        // Queues up task in a single thread executor
        Executors.newSingleThreadExecutor().execute(Main::helloWorld);
        // Caches tasks so that short lived re-occurring tasks can execute faster
        Executors.newCachedThreadPool().execute(Main::helloWorld);
        // Runs in a separate thread pool with the given delay
        Executors.newScheduledThreadPool(2).schedule(Main::helloWorld, 10, TimeUnit.MILLISECONDS);
https://dzone.com/articles/java-holiday-calendar-2016-day-15-dont-optimize-no
The JVM will collect statistics on how methods are used and then use that piece of information when it eventually compiles the method with its Just-In-Time (JIT) compiler. This often takes place when a method has been called for about 10,000 times. This is one reason why we should "warm up" our code properly before we run benchmarks.

The JVM is also using a scheme called Code Flattening , which means that it is able to "roll up" method calls and consider the code as a larger flow of operations. This way, it is able to determine the possible paths the program can take and consider these paths individually and optimize them. For example, identical range checking that takes place in several methods that call each other can be eliminated. Another example is that dead paths (e.g. where an "if"-branch is using a constant expression) can be eliminated altogether.
Another means of optimization is Escape Analysis, which is used to determine if an object is visible outside a certain scope. If not, the object can be allocated on the stack rather than on the heap, making the program run much faster. 
One cool thing is that the JVM can combine its optimization schemes. For example, with code flattening, much larger scopes can be used for escape analysis, and objects that actually do escape a method might be re-catch on a higher "rolled up" level. Such objects may be subject to stack allocation too.
https://dzone.com/articles/definition-of-the-trait-pattern-in-java
“Traits both provide a set of methods that implement behaviour to a class and require that the class implement a set of methods that parameterize the provided behaviour”
The following properties are named as distinctive for traits:
  • traits can be combined (symmetric sum)
  • traits can be overriden (asymmetric sum)
  • traits can be expanded (alias)
  • traits can be excluded (exclusion)

public interface HasComments<R extends HasComments<R>> {
    // one method that parameterize the provided behaviour
    List<Comment> getComments();
    // two methods that implement the behaviour
    default R add(Comment comment) {
        getComments().add(comment);
        return (R) this;
    }
    default R remove(Comment comment) {
        getComments().remove(comment);
        return (R) this;
    }
}


public final class Lazy<T> {
    private volatile T value;
    public T getOrCompute(Supplier<T> supplier) {
        final T result = value;  // Read volatile just once...
        return result == null ? maybeCompute(supplier) : result;
    }
    private synchronized T maybeCompute(Supplier<T> supplier) {
        if (value == null) {
            value = requireNonNull(supplier.get());
        }
        return value;
    }
}
https://dzone.com/articles/java-holiday-calendar-2016-day-3-initializing-maps-1
http://minborgsjavapot.blogspot.com/2014/12/java-8-initializing-maps-in-smartest-way.html
With Java 9, we will get even better ways of creating immutable Maps. Until then, by defining two utility methods...
    public static <K, V> Entry<K, V> entry(K key, V value) {
        return new AbstractMap.SimpleEntry<>(key, value);
    }
    public static <K, U> Collector<Entry<K, U>, ?, Map<K, U>> entriesToMap() {
        return Collectors.toMap(Entry::getKey, Entry::getValue);
    }
...you can do this:
protected static Map<Integer, String> createMap() {
        return Stream.of(
                entry(0, "zero"),
                entry(1, "one"),
                entry(2, "two"),
                entry(3, "three"),
                entry(4, "four"),
                entry(5, "five"),
                entry(6, "six"),
                entry(7, "seven"),
                entry(8, "eight"),
                entry(9, "nine"),
                entry(10, "ten"),
                entry(11, "eleven"),
                entry(12, "twelve")).
                collect(entriesToMap());
    }


https://www.programcreek.com/2014/05/top-10-mistakes-java-developers-make/
#1. Convert Array to ArrayList
ArrayList, developers often do this:
List<String> list = Arrays.asList(arr);

Arrays.asList() will return an ArrayList which is a private static class inside Arrays, it is not the java.util.ArrayList class. The java.util.Arrays.ArrayList class has set(), get(), contains() methods, but does not have any methods for adding elements, so its size is fixed. To create a real ArrayList, you should do:

ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));

#2. Check If an Array Contains a Value

Developers often do:

Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
The code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:

Arrays.asList(arr).contains(targetValue);

#5. Use Raw Type of Collection
In Java, raw type and unbounded wildcard type are easy to mixed together. Take Set for example, Set is raw type, while Set<?> is unbounded wildcard type.
Consider the following code which uses a raw type List as a parameter:
public static void add(List list, Object o){
 list.add(o);
}
public static void main(String[] args){
 List<String> list = new ArrayList<String>();
 add(list, 10);
 String s = list.get(0);
}
This code will throw an exception:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
 at ...
Using raw type collection is dangerous as the raw type collections skip the generic type checking and not safe. There are huge differences between SetSet<?>, and Set<Object>. Check out
Raw type vs. Unbounded wildcard and Type Erasure.


http://stackoverflow.com/questions/362424/accessing-constructor-of-an-anonymous-class
From the Java Language Specification, section 15.9.5.1:
An anonymous class cannot have an explicitly declared constructor.
As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:
public class Test {
    public static void main(String[] args) throws Exception {
        final int fakeConstructorArg = 10;

        Object a = new Object() {
            {
                System.out.println("arg = " + fakeConstructorArg);
            }
        };
    }
}
http://stackoverflow.com/questions/481813/how-to-simplify-a-null-safe-compareto-implementation
private static Comparator<String> nullSafeStringComparator = Comparator
        .nullsFirst(String::compareToIgnoreCase); 

private static Comparator<Metadata> metadataComparator = Comparator
        .comparing(Metadata::getName, nullSafeStringComparator)
        .thenComparing(Metadata::getValue, nullSafeStringComparator);

public int compareTo(Metadata that) {
    return metadataComparator.compare(this, that);
}
you can simply use Apache Commons Lang:
result = ObjectUtils.compare(firstComparable, secondComparable)
http://stackoverflow.com/questions/23612864/create-a-zip-file-in-memory
Use ByteArrayOutputStream with ZipOutputStream to accomplish the task.
you can use ZipEntry to specify the files to be included into the zip file.
Here is an example of using the above classes,
String s = "hello world";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ZipOutputStream zos = new ZipOutputStream(baos)) {

  /* File is not on the disk, test.txt indicates
     only the file name to be put into the zip */
  ZipEntry entry = new ZipEntry("test.txt"); 

  zos.putNextEntry(entry);
  zos.write(s.getBytes());
  zos.closeEntry();

  /* use more Entries to add more files
     and use closeEntry() to close each file entry */

  } catch(IOException ioe) {
    ioe.printStackTrace();
  }
now baos contains your zip file as a stream
http://stackoverflow.com/questions/2127318/java-how-can-i-do-dynamic-casting-of-a-variable-from-one-type-to-another
    Class<? extends Number> theClass = Class.forName(theType).asSubclass(Number.class);
    Number obj = theClass.cast(something);
InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));
http://jdevelopment.nl/trywithresources-jdk7-scoped-declarations/
try (InputStream in = createInputStream(); OutputStream out = 
      createOutputStream()) {
   /* Copy data here */
}
The InputStream and OutputStream are automatically closed at the end of the try-with-resources block. If an exception is thrown during the main block and then again during the closing of one (or both) of the streams, the exception on the close operation is added to the original exception as a suppressed exception, so no exceptions are swallowed silently anymore. The try-with-resources blocks are also not limited to be used for in- and output streams, but can be used on any object that implements the AutoCloseable interface.

There is one minor disadvantage to the try-with-resource statement, it is required to define the variable that refers to the object to be closed within the brackets after the try. 

I would propose the following workaround for this situation:
public void readData(InputStream in) {
   try(InputStream autoCloseableInputStream = in) {
      int input;
      while((input = in.read()) >=0) {
         //Use input here
      }
   }
}


This code does compile and the stream is automatically closed at the end of the try block. Since the autoCloseableInputStream and in variables refer to the exact same object, it is not necessary to actually use the autoCloseableInputStream variable in the code. Using a name like autoCloseableInputStream makes it clear that this variable is only defined in order to be able to use the try-with-resources statement.

While your code is correct, I believe that it should not be used normally, the closing of resource should be done normally in the scope where this resource has been created. The method readData should normally return an Exception and if captured in the caller code (that created the InputStream) then the try catch should close the resource.

It is the same problem as where to catch the Exception and how to deal with them.
http://stackoverflow.com/questions/11216994/why-does-java-not-allow-foreach-on-iterators-only-on-iterables
Because the "for" loop would be destructive to the iterator. Iterator cannot be reset (ie. moved back to the beginning) unless it implements the ListIterator subinterface.
http://stackoverflow.com/questions/1513520/why-are-all-fields-in-an-interface-implicitly-static-and-final
An interface can't have behavior or state because it is intended to specify only an interaction contract, no implementation details. No behavior is enforced by not allowing method/constructor bodies or static/instance initializing blocks. No state is enforced by only allowing constants. A constant in Java is defined by a static final field (and by convention the name uses UPPER_CASE_AND_UNDERSCORES).
javadoc
http://checkstyle.sourceforge.net/config_javadoc.html#JavadocStyle
  • Check for allowed HTML tags. The list of allowed HTML tags is "a", "abbr", "acronym", "address", "area", "b", "bdo", "big", "blockquote", "br", "caption", "cite", "code", "colgroup", "dd", "del", "div", "dfn", "dl", "dt", "em", "fieldset", "font", "h1" to "h6", "hr", "i", "img", "ins", "kbd", "li", "ol", "p", "pre", "q", "samp", "small", "span", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thread", "tr", "tt", "u", "ul".
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html
Comments are written in HTML - The text must be written in HTML, in that they should use HTML entities and can use HTML tags. You can use whichever version of HTML your browser supports; we have written the standard doclet to generate HTML 3.2-compliant code elsewhere (outside of the documentation comments) with the inclusion of cascading style sheets and frames. (We preface each generated file with "HTML 4.0" because of the frame sets.)
The list of allowed HTML tags is hardcoded in the JavadocStyle Checkstyle check (verified by looking at the Checkstyle 5.6 sources). So if you want to keep the check for its other good properties, you will have to live with the restricted set of HTML tags. One workaround for the underline problem is to use CSS (which is allowed) like this:
<span style="text-decoration:underline;">underlined text</span>
http://stackoverflow.com/questions/4394978/copy-fields-between-similar-classes-in-java
You could use the BeanUtils class in the Spring Framework to do this. It may not necessarily be any more efficient than your reflection-based technique, but it's certainly simple to code. I expect that all you would need to do is:
BeanUtils.copyProperties(source, target);
If that doesn't suit, you could also consider using BeanWrapper / BeanWrapperImpl in the Spring Framework to iterate through the properties of your classes. That would be simpler than using low-level reflection APIs.
you just convert the Class A to json string. Then convert jsonString to you subClass (CopyA) .using below code:
Gson gosn = new Gson();
String tmp = gson.toJson(a);
CopyA myObject = gson.fromJson(tmp,CopyA.class);
If you don't mind using a third party library, BeanUtils from Apache Commons will handle this quite easily, using copyProperties(Object, Object).

How to overwrite javadoc inherited from base class.
- Put javadoc first then before @Override
  • Explicitly inherit comment with {@inheritDoc} tag - Insert the inline tag {@inheritDoc} in a method main description or @return@param or @throws tag comment -- the corresponding inherited main description or tag comment is copied into that spot.The source file for the inherite
javadoc tag: <br> <p> no end /
http://stackoverflow.com/questions/15905127/overridden-methods-in-javadoc
/**
 * @inheritDoc
 *
 * This implementation is very, very slow when b equals 3.
 */
public foo(int b)
{ ... }

Bytes to string
String s = new String(bytes);
Not - String.value(bytes) - this will be the address of the bytes
- it calls String.value(Object o) method which calls object.toString(). byte[] toString() is the address.

Basic hot swap:
http://www.mkyong.com/eclipse/how-to-configure-hot-deploy-in-eclipse/
2.1 Double clicks on the Tomcat plugin, refer to publishing tab, make sure Automatically publish when resources change is selected. This should be the default option, to support “hot deploy” resources, for example : JSP, XML and properties files.

2.2 In the Tomcat Plugin page, clicks on the Module view, make sure Auto Reload is Disabled. Default is enabled.
This is an important step, failed to set the auto reload to disabled, the Tomcat server will be restarted every time you modified something!

Hot deploy has supported the code changes in the method implementation only. If you add a new class or a new method, restart is still required.
http://ssledz.github.io/blog/2016/05/16/hot-swap-in-java-with-dcevm-and-hotswapagent-a-jrebel-free-alternative/
-XXaltjvm=dcevm
Dynamic Code Evolution 64-Bit Server VM (build 25.71-b01-dcevmlight-10, mixed mode)

HotswapAgent does the work of reloading resources and framework configuration.
http://tirthalpatel.blogspot.com/2014/06/steps-to-setup-hotswap-agent-in-eclipse.html
https://github.com/HotswapProjects/HotswapAgent/wiki/Eclipse-setup
Step-3: Tomcat - Add "-XXaltjvm=dcevm -javaagent:\HotswapAgent.jar" in VM Arguments.
https://github.com/HotswapProjects/HotswapAgent
add following command line java attributes: -XXaltjvm=dcevm -javaagent:PATH_TO_AGENT\hotswap-agent.jar

http://stackoverflow.com/questions/7054972/java-system-properties-and-environment-variables
System properties are set on the java command line using the -Dpropertyname=value syntax. They can also be added at runtime using System.setProperty(name, value) or via the various System.getProperties().load() methods
Environment variables are set in the OS, eg in linux export HOME=/Users/myusername or on windows SET WINDIR=C:\Windows etc, and, unlike properties, may not be set at runtime.
https://blog.jetbrains.com/idea/2013/07/get-true-hot-swap-in-java-with-dcevm-and-intellij-idea/

java list remove last n elements
http://stackoverflow.com/questions/10797663/removing-tail-of-x-elements-from-a-list
subList(list.size() - N, list.size()).clear() is the recommended way to remove the last Nelements. Indeed, the Javadoc for subList specifically recommends this idiom:
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:
 list.subList(from, to).clear();
http://stackoverflow.com/questions/5682625/why-do-integer-div-and-mod-round-towards-zero
Unlike in C, in Java is the result of x/y and x%y well-defined even for negative operands. Surprisingly, it's defined by rounding towards zero, and not by rounding down (i.e., towards negative infinity). Does anybody have taken any advantage of this definition?
It's easier to implement a division routine if you can round toward zero. Often, a division involving a negative is sign-flipped, and then the division carried out on a positive equivalent, and then the answer flipped back again. So the effect is naturally going to be round toward zero.
http://stackoverflow.com/questions/4403542/how-does-java-do-modulus-calculations-with-negative-numbers
Since "mathematically" both are correct:
-13 % 64 = -13 (on modulus 64)  
-13 % 64 = 51 (on modulus 64)
One of the options had to be chosen by Java language developers and they chose:
the sign of the result equals the sign of the dividend.
Says it in Java specs:
https://java.net/projects/tda
https://spotify.github.io/threaddump-analyzer/
       // copying array org to copy
       // Here, new array has 5 elements - two
       // elements more than the original array
       int[] copy = Arrays.copyOf(org, 5);
        Arrays.sort(arr, Collections.reverseOrder());
        // Sorting a list of students in descending order of
        // roll numbers using a Comparator that is reverse of
        // Sortbyroll()
        Comparator c = Collections.reverseOrder(new Sortbyroll());
        Collections.sort(ar, c);

public static void shuffle(List<?> list) {
    Random rnd = r;    if (rnd == null)
        r = rnd = new Random(); // harmless race.    shuffle(list, rnd);}

  • This method works by randomly permuting the list elements
  • Runs in linear time. If the provided list does not implement the RandomAccess interface, like LinkedList and is large, it first copies the list into an array, then shuffles the array copy, and finally copies array back into the list. This makes sure that the time remains linear.
  • It traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the “current position”. Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive. [Source : javadoc]
public static void shuffle(List<?> list, Random rnd) {
    int size = list.size();    if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=size; i>1; i--)
            swap(list, i-1, rnd.nextInt(i));    } else {
        Object arr[] = list.toArray();
        // Shuffle array        for (int i=size; i>1; i--)
            swap(arr, i-1, rnd.nextInt(i));
        // Dump array back into list        // instead of using a raw type here, it's possible to capture        // the wildcard but it will require a call to a supplementary        // private method        ListIterator it = list.listIterator();        for (int i=0; i<arr.length; i++) {
            it.next();            it.set(arr[i]);        }
    }
}
https://helpx.adobe.com/experience-manager/kb/TakeThreadDump.html
To obtain a thread dump using jstack, run the following command:
jstack <pid>
You can output consecutive thread dumps to a file by using the console output redirect/append directive:
jstack <pid> >> threaddumps.log

jstack script

Here's a script, taken from eclipse.org that will take a series of thread dumps using jstack.  It also takes the thread level cpu usage using top command as well.
#!/bin/bash
if [ $# -eq 0 ]; then
    echo >&2 "Usage: jstackSeries <pid> <run_user> [ <count> [ <delay> ] ]"
    echo >&2 "    Defaults: count = 10, delay = 0.5 (seconds)"
    exit 1
fi
pid=$1          # required
user=$2         # required
count=${3:-10}  # defaults to 10 times
delay=${4:-0.5} # defaults to 0.5 seconds
while [ $count -gt 0 ]
do
    sudo -u $user top -H -b -n1 -p $pid >top.$pid.$(date +%H%M%S.%N) &
    sudo -u $user jstack -l $pid >jstack.$pid.$(date +%H%M%S.%N)
    sleep $delay
    let count--
    echo -n "."
done


Just run it like this:
sh jstackSeries.sh [pid] [cq5serveruser] [count] [delay]
For example:
sh jstackSeries.sh 1234 cq5serveruser 10 3
  • 1234 is the pid of the Java process
  • cq5serveruser is the Linux or UNIX user that the Java process runs as
  • 10 is how many thread dumps to take
  • 3 is the delay between each dump

1) Note the process ID number of the Java process (e.g. using top, a grep on ps -axw, etc.) and send a QUIT signal to the process with the kill -QUIT or kill -3 command. For example:
   kill -3 JAVA_PID


    PriorityQueue<Integer> maxPQ = new PriorityQueue<Integer>(20,Collections.reverseOrder());

http://stackoverflow.com/questions/7467313/why-are-readobject-and-writeobject-private-and-why-would-i-write-transient-vari
(1) The methods are not declared in any class or interface. A class, that implements the Serializable interface and requires special special handling during the serialization and deserialization process must implement those methods and the serializer/deserializer will try to reflect those methods.
This is one of the rather strange corners in Java where the API is actually defined in the javaDoc... But if the methods had been defined in an interface, then they had to be public (we can't implement an interface method an lock it by adding a private modifier).
Why private - the javaDoc does not give a hint. Maybe they are specified as private because no other class but the implementor is intended to use them. They are private by definition.
We don't want these methods to be overridden by subclasses. Instead, each class can have its own writeObject method, and the serialization engine will call all of them one after the other. This is only possible with private methods (these are not overridden). (The same is valid for readObject.)

http://stackoverflow.com/questions/7034748/findbugs-wants-readobject-to-be-private-for-serialization-why
In order for your method to be called by objectInputStream.readObject(), you must declare it private:
private void readObject(ObjectInputStream objectInputStream)
If you do not, your method will not be called (put a break point in there to prove this). Your code may appear to work but that is because the default serialization is being used.
You might be wanting to make this protected to allow for subclassing but this is not needed. The serialization process automatically calls the readObject of the base class prior to calling the readObject of the concrete class. This happens even if the concrete class does not make a call to:
objectInputStream.defaultReadObject();
...contrary to other posts I have read on the web. The same applies to the writeObject methods as well.

http://stackoverflow.com/questions/1883345/whats-up-with-javas-n-in-printf
String.format("%n")
There is also one specifier that doesn't correspond to an argument. It is "%n" which outputs a line break. A "\n" can also be used in some cases, but since "%n" always outputs the correct platform-specific line separator, it is portable across platforms whereas"\n" is not.
http://stackoverflow.com/questions/15133549/difference-between-yyyy-and-yyyy-in-nsdateformatter
@"YYYY" is week-based calendar year.
@"yyyy" is ordinary calendar year.
A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
"YYYY-'W'ww-u"2001-W27-3
yyyy-MM-dd not YYYY-MM-dd
DateTimeFormatter

Exception in thread "main" java.time.format.DateTimeParseException: Text '2016-09-20' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=9, DayOfMonth=20, WeekBasedYear[WeekFields[SUNDAY,1]]=2016},ISO of type java.time.format.Parsed
http://stackoverflow.com/questions/8882097/is-there-a-way-to-calculate-the-intersection-of-two-sets
Use the retainAll() method of Set:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
If you want to preserve the sets, create a new set to hold the intersection:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

https://dzone.com/articles/upgrade-your-code-conventions-2
Don’t Start Test Methods With the Word “Test”
Working Code > Performant Code
Use Your Own Exception Type
“Most programmers ignore checked exceptions and leave them unnoticed”

http://tengfei.tech/2016/06/11/How-does-looping-order-affect-the-performance-of-a-2D-array/
How does the order of the loops affect performance when iterating over a 2D array?
1
2
3
4
5
6
7
int[][] array = new int[100][100];
for(int i = 0 ; i < 100 ; i++ ){
    for(int j = 0 ; j < 100 ; j++ ){
        System.out.printlin(array[j][i]); // column first
        System.out.printlin(array[i][j]); // row first
    }
}

In computer programming, an Iliffe vector, also known as a display, is a data structure used to implement multi-dimensional arrays. An Iliffe vector for an n-dimensional array (where n ≥ 2) consists of a vector (or 1-dimensional array) of pointers to an (n − 1)-dimensional array. They are often used to avoid the need for expensive multiplication operations when performing address calculation on an array element. They can also be used to implement jagged arrays, such as triangular arraystriangular matrices and other kinds of irregularly shaped arrays. The data structure is named after John K. Iliffe.
Their disadvantages include the need for multiple chained pointer indirections to access an element, and the extra work required to determine the next row in an n-dimensional array to allow an optimising compiler to prefetch it. Both of these are a source of delays on systems where the CPU is significantly faster than main memory.
The Iliffe vector for a 2-dimensional array is simply a vector of pointers to vectors of data, i.e., the Iliffe vector represents the columns of an array where each column element is a pointer to a row vector.
Multidimensional arrays in languages such as JavaPython (multidimensional lists), RubyVisual Basic .NETPerlPHPJavaScriptObjective-C (when using NSArray, not a row-major C-style array), Swift, and Atlas Autocode are implemented as Iliffe vectors.
Iliffe vectors are contrasted with dope vectors in languages such as Fortran, which contain the stride factors and offset values for the subscripts in each dimension.

But why does this matter? All memory accesses are the same, right?
NO. Because of CPU caches.
CPU cache is a hardware cache used by the Central Processing Unit (CPU) of a computer to reduce the average time to access data from the main memory. The cache is a smaller, faster memory which stores copies of the data from frequently used main memory locations.
Data from memory gets brought over to the CPU in little chunks (called ‘cache lines’), typically 64 bytes. If you have 4-byte integers, that means you’re getting 16 consecutive integers in a neat little bundle. It’s actually fairly slow to fetch these chunks of memory.
If you access the data in a consecutive memory order, every time you access a variable, it will directly read from CPU cache. 100*100/16 times fetches from memory.
But if you access the data in a nonconsecutive memory order, it will fetch the data from memory to CPU cache. 100*100 times fetches from memory.
It is very obvious that which way is more efficient.
http://www.wikiwand.com/en/Array_data_structure

Multidimensional arrays

For multi dimensional array, the element with indices i,j would have address B + c · i + d · j, where the coefficients c and d are the row and column address increments, respectively.
More generally, in a k-dimensional array, the address of an element with indices i1i2, ..., ik is
B + c1 · i1 + c2 · i2 + ... + ck · ik.
For example: int a[2][3];
This means that array a has 2 rows and 3 columns, and the array is of integer type. Here we can store 6 elements they are stored linearly but starting from first row linear then continuing with second row. The above array will be stored as a11, a12, a13, a21, a22, a23.

http://stackoverflow.com/questions/12301570/javax-annotation-nullable-vs-checkfornull
FindBugs will ignore @Nullable.
In practice this annotation is useful only for overriding an overarching NonNull annotation.
Use @CheckForNull in the cases when the value must always be checked. Use @Nullable where null might be OK.

http://www.codejava.net/coding/how-to-calculate-md5-and-sha-hash-values-in-java
private static String hashString(String message, String algorithm)
        throws HashGenerationException {
    try {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        byte[] hashedBytes = digest.digest(message.getBytes("UTF-8"));
        return convertByteArrayToHexString(hashedBytes);
    catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
        throw new HashGenerationException(
                "Could not generate hash from String", ex);
    }
}
private static String convertByteArrayToHexString(byte[] arrayBytes) {
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < arrayBytes.length; i++) {
        stringBuffer.append(Integer.toString((arrayBytes[i] & 0xff) + 0x10016)
                .substring(1));
    }
    return stringBuffer.toString();
}

https://www.mkyong.com/java/java-md5-hashing-example/
http://www.rgagnon.com/javadetails/java-0416.html

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts