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

- 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.

- 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
- 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.


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

- an object that can monitor multiple channels for events
- FileChannel,FileChannel,DatagramChannel,ServerSocketChannel
- 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 (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.

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 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.
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.

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?
Post a Comment


Java (159) Lucene-Solr (110) All (60) Interview (59) J2SE (53) Algorithm (37) Eclipse (35) Soft Skills (35) Code Example (31) Linux (26) JavaScript (23) Spring (22) Windows (22) Web Development (20) Tools (19) Nutch2 (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (9) Continuous Integration (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Design (8) Dynamic Languages (8) Http Client (8) Maven (8) Security (8) Trouble Shooting (8) bat (8) blogger (8) Big Data (7) Google (7) Guava (7) JSON (7) Problem Solving (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) IDE (5) Lesson Learned (5) Miscs (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) OpenNLP (4) Project Managment (4) Python (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Firefox (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Google Drive (2) Gson (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Bit Operation (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Troubleshooting (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts