Java Basics


The Get and Put Principle
- "Producer Extends, Consumer Super"
- use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don’t use a wildcard when you both get and put.
public static <T> void copy(List<? super T> dest, List<? extends T> src)

Type erasure
- fix it - pass class type
- no way to find out the runtime type of generic type parameters in Java
- pass the Class of the type parameter
- create(Class<T> type)
new ArrayList<Integer>().getClass() == new ArrayList<String>().getClass(); // true
Difference between ArrayList<? extends T> and ArrayList<? super T>

Unbounded Wildcards - Class<?>
printList(List<?> list)
List<Object> and List<?> are not the same.
- can only insert null into a List<?>.

Upper Bounded Wildcards -- List<? extends Foo> list
- List<Number> is more restrictive than List<? extends Number>
Lower Bounded Wildcards -- List<? super Integer> list

NoClassDefFoundError
- it's an Error - LinkageError
- class was present during time of compilation but not available at runtime when class loader is trying to load it
- error on static initializer block can also result in NoClassDefFoundError.

ClassNotFoundException
- checked exception - must handled in the code
- load a class in runtime using Reflection, such as Class.forName(), ClassLoader.loadClass()

prefer double over float
- float: single (32 bit) precision
- double: double (64 bit) precision

Static method
- static method is always resolved at compile time by using Type of reference variable
- can not access non static member inside static context
- static variables are also not serialized During Serialization

Why String is immutable
String Pool
Multithreading Benefits
Optimization and Performance
- hashcode is cached
HashMap keys

Service provider interface (SPI)
- an API intended to be implemented or extended by a third party
Service Provider
ServiceLoader
- Load drivermanager

Checked vs RuntimeException
- Use exceptions only for exceptional scenarios
- Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
- Use checked exceptions when want to force to client to think how to handle the recoverable exceptional situation. Otherwise use RuntimeException

- Avoid unnecessary use of checked exceptions
- Favor the use of standard exceptions
- If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
- Don't use Exceptions for control flow
- Use a checked exception for conditions client code can reasonably be expected to handle.

RXjava Exceptions.propagate()
- throw a RuntimeException and Error directly or wrap any other exception type into a RuntimeException.
Thread.setDefaultUncaughtExceptionHandler(handler);

String.CASE_INSENSITIVE_ORDER

Java NIO
Stream Oriented vs. Buffer Oriented
Blocking vs. Non-blocking IO
- only get what is currently available, or nothing at all
- not wait for it to be fully written

Selectors
- an object that can monitor multiple channels for events
Channels
- FileChannel,FileChannel,DatagramChannel,ServerSocketChannel
Buffers
- ByteBuffer, CharBuffer, IntBuffer,LongBuffer,ShortBuffer

Why can't we define a static method in an interface?
Suppose we could do it, if interface A declares methodF, two class B, C both implement interface A. then if we can interfaceA.methodF(), what implementation it should call. JVM just can't figure it out.
Annotations
Annotations (also known as metadata) provide a formalized way to add information to the code so later other tools can easily use these metadata.
Annotations themselves are hardly more useful than comments, more valuable thing is the tools that read and process them.
Annotations are partly motivated by a general trend toward combining metadata with source-code files, instead of keeping it in external documents. In many cases, this can simplify maintenance significantly.
It can provide cleaner looking code, compile-time checking, IDE support, annotation API to get and process these added information.
Annotations are widely used by frameworks such as web services, EJB3, hibernate, that require some sort of additional information to accompany your source code.

Multithread
Why double checked locking doesn't work in Java?
Double checked locking in java is usually implemented like the following:
public class Singleton {
    private Singleton instance;
    public static Singleton getInstance() {
     if (instance == null) {
       synchronized(this) {
         if (instance == null) {
           instance = new Singleton ();
         }
       }
     }
     return this.theGadget;
    }
}
The main reason is that the new operation is not atomic.
At First, one thread pass the null check and tries to initialize the object, because the new operation is not atomic, the process - start allocating and writing the object to the field, contains several writes to memory without guaranteed ordering.
During this period, another thread can come in, see the partially written object.
It would pass the null check, and return the partially allocated object. This can happen with objects, longs type on a 32-bit platform.

ThreadLocal
Definition
ThreadLocal is used to create thread-local variable, each thread will have its own Thread Local variable. One thread can not access/modify other thread’s Thread Local variables, meanwhile they can be accessed from anywhere inside that thread.
ThreadLocal provides get and set accessor methods that maintain a separate copy of the value for each thread that uses it. When a thread calls ThreadLocal.get for the first time, initialValue is consulted to provide the initial value for that thread.
ThreadLocal can be used as an alternative to synchronization to improve scalability and performance. Classes encapsulated in ThreadLocal are automatically thread-safe in a pretty simple way, since it’s clear that anything stored in ThreadLocal is not shared between threads.
When to use ThreadLocal?
ThreadLocal can be used as an alternative to synchronization. In some cases, this can improve scalability and performance significantly.
ThreadLocal can be used to reuse non-trivial objects, just as a resource/object pool.
ThreadLocal is widely used in implementing application frameworks to maintain some context related to the current thread.
For example, J2EE containers use ThreadLocal to associate a transaction context with an executing thread for the duration of an EJB call.
Caveats
It is easy to abuse ThreadLocal by treating its thread confinement property as a license to use global variables or as a means of creating "hidden" method arguments.
Thread-local variables can detract from reusability and introduce hidden couplings among classes, and should therefore be used with care.


Resource
Think in Java (4th Edition)
Oracle JRockit: The Definitive Guide
Thread-local variables in Java
Java Thread Local – How to Use and Code Sample
When and how should I use a ThreadLocal variable?

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)