Eclipse RCP Miscs Series 2

Eclipse RCP Miscs Series 2

Perspective listener
-- Define the behavior what to do when perspective is activated or changed.
IWorkbenchWindow.addPerspectiveListener(IPerspectiveListener listener) and removePerspectiveListener(IPerspectiveListener listener).

Allow user to bring job dialog back
After checked the Checkbox "always run in background", there would be no way to re-show it, so RCP application should define one preference to allow user to reshow the dialog.
    protected void createFieldEditors()
       runInBackground = new BooleanFieldEditor(
           "Always run in background",
    public boolean performOk()
               .setValue(IPreferenceConstants.RUN_IN_BACKGROUND, runInBackground.getBooleanValue());
       catch (IOException e)
       return super.performOk();
ToolTip for TreeItem

Since SWT/JFace 3.3, your TreeViewer's lable provider can extend ColumnLabelProvider, and implement the cool getTooltip() methods, and enable it by ColumnViewerToolTipSupport.enableFor (viewer);

1. Outside of your rcp project, type
org.sonatype.tycho:maven-tycho-plugin:generate-poms -DgroupId=se.mattiasholmqvist -Dtycho.targetPlatform=~/dev/eclipse-3.6.1-delta/
This will create a pom.xml for the current directory (parent project) and a pom.xml for each eclipse project.
2. Building the product
clean package -Dtycho.targetPlatform=~/dev/eclipse-3.6.1-delta/

Export product to other platforms
1. Download and install Eclipse DelatPack
In the page,, search DeltaPack.
2. Configure org.sonatype.tycho/maven-osgi-packaging-plugin in pom.xml: set the environment values for the target platform.
You can get these values form the delta pack:
For instance, from
org.eclipse.equinox.launcher.motif.aix.ppc_1.1.0.v20100503, we can see to build a AIX product:
ws should be motif, os should be aix, arch should be ppc.

A concrete example:

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?

Remember Knowledge Is Power

Remember Knowledge Is Power

Ten years ago, I didn't write any diary.
Four years ago, when I worked as an intern at one company, I observed and realized that when I asked questions to my mentor, she can always quickly find the answer from her computer diary.

I thought this was really a good habit, and began to write diary.
But at first I usually just write them and forget them, rarely review them.

Three yeas ago, I began to try to blog in English as a way to improve my English writing skills.
Write down some notes and review then up when I needed them.

Recently, when we discussed one problem with my colleague, he tried to type the one a-little-complex command. Usually I do this by copy and paste. But my colleague tried to analyze and remember this command when he was typing. This reminded me that how many times that I Google searched, and found some solutions, some commands, or even posted to my blog, but I just can't remember them, next time, I had to do Google search or look up in my blog again. This was so inefficient, and wasted my time. So if these information and solutions are really valuable, why I don't try to remember them.

I really should try to remember more, remember them when I am using them - of course, not all knowledge is worthy remembering.
This sway, I can save time, work more efficiently, provide answer/solution more quickly, and can make me look cooler and smarter :)

Also one of my colleagues is really very cute, seems he is really good at remembering things, defect number, event date and etc, I Admire him.

I really should read some books about how to improving memory, how to use my whole brain during studying and working, improve these abilities, and improve my skills to do, study and work effectively.

Bug Analysis Part 1

Bug Analysis Part 1

- StreamCorruptedException: unexpected block data

We met a field defect recently, client sent a command to server, but didn't get response. At Server there was no log indicating that it received the command.

At first, we thought it maybe a network related problem, as from client logs, we can see user tried same command several times, and run this command immediately after connected to server.

From server logs, we can see each time, after connection was created successfully and the application tried to read command, the application would throw 'StreamCorruptedException: unexpected block data ', and connection would be closed.

But we can't understand that if it’s a network connection problem, why it happened so frequently.
And we shouldn't blame the network easily, without real evidence, right?

From this book Debug It!, we learn that - it’s too easy to point the finger of blame to other components or hardware, we should suspect your own code first.

Meanwhile we didn't find some obvious problems about network.

What we should do next?
One of the most important skills for problem analysis is to think divergently, come up all possibilities, and check and test then in the order of probability.

Look at the Javadoc, StreamCorruptedException:
Thrown when control information that was read from an object stream violates internal consistency checks.

Maybe the connection was good, but only this type of command failed. – We should look at the log: does this client ever successfully executed one of this type of command, does it successfully executed other types of command?

Are the client and server version same and compatible? Version mismatch is a common source of bug in client/server application.

So check the version of client and server. Yep, it's different, client is new, and server is old.

What to do next?
In Debug It!, it teaches us that Always Reproduce the Problem First.
Sometimes we think we are just smart and we can find the root cause of the problem just by thinking, but if we can't reproduce it, how we can verify what we think is really the root cause, and how to verify that our fix does fix the problem in future.
Or sometimes, we are just lazy, as trying to reproduce the problem is usually not easy.
But this always pay off, as if we can find the way to produce the problem, then finding the root cause and fixing it would be easy.
Remember to use exact same version application as one used in client environment is important.

So next we used exact same client/server application and executed the command. Immediately we recreated the problem!

Next part is about the technical stuff.
Simply put, the reason is because in new version client, the command implementation changes, it introduces a new command class, and sends the new command object to server.

The old server doesn't have this command class, and can't deserialize the command object.

But normally, if one class is missing, java deserialization should throw ClassNotFoundException, why StreamCorruptedException? Is our analysis correct?

To figure it the reason, we wrote a simple java application, it writes the command object to the file, and reads it back.

During deserialization, we deleted the new command class, it does throw the StreamCorruptedException.

Check the source code, we figure it out this may be because the command overrides readObject and writeObject.

Sample code:
public class Deserialization
    public static void main(String[] args) throws Exception

    private static void writeZippedObject() throws FileNotFoundException, IOException, SecurityException,
       FileOutputStream fos = new FileOutputStream("command");
       GZIPOutputStream gos = new GZIPOutputStream(fos);
       ObjectOutputStream oos = new ObjectOutputStream(gos);

       Method method = Math.class.getMethod("sqrt", new Class[] { double.class });
       Command command = new ConfigCommand(method, new Object[] { Integer.valueOf(4) });
       System.out.println("write command: " + command);

    private static void readZippedObject() throws FileNotFoundException, IOException, ClassNotFoundException
       FileInputStream fis = new FileInputStream("command");
       GZIPInputStream gis = new GZIPInputStream(fis);
       ObjectInputStream ois = new ObjectInputStream(gis);

       Command command = (Command) ois.readObject();
       System.out.println("read command: " + command);

class Command implements Serializable
    private static final long serialVersionUID = 1L;
    private String serviceString = null;
    private String methodName = null;
    protected Object[] params = null;

    public Command(Method method, Object[] params)
       methodName = method.getName();
       Class service = method.getDeclaringClass();
       serviceString = service.getName();
       this.params = params;

    private Map fieldsTable = new HashMap();

    public String toString()
       return "[serviceString: " + serviceString + ", methodName: " + methodName + "]";

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
       fieldsTable = (HashMap) in.readObject();
       serviceString = (String) fieldsTable.get("serviceString");
       methodName = (String) fieldsTable.get("methodName");
       params = (Object[]) fieldsTable.get("params");

    private void writeObject(ObjectOutputStream out) throws IOException
       fieldsTable.put("serviceString", serviceString);
       fieldsTable.put("methodName", methodName);
       fieldsTable.put("params", params);

class ConfigCommand extends Command
    public ConfigCommand(Method method, Object[] params)
       super(method, params);
    private static final long serialVersionUID = 1L;

Without readObject/writeObject in Command class and ConfigCommand class, it would throw ClassNotFoundException.

With these 2 serialization-related methods, deserialization without the ConfigCommand would throw ‘StreamCorruptedException: unexpected block data’:
Exception in thread "main" unexpected end of block data
    at objectio.Deserialization.readZippedObject(
    at objectio.Deserialization.main(

Lesson Learned
Know your code well, and know its change history well, write them down.
If we know the implementation of this command changed significantly, we might find out the root cause faster.

Read defect description carefully, but keep your mind open, the report might not give too much information, or even give misleading or wrong information.

Think whether the same problem may occur elsewhere, and ensure it not occur again.

Why this bug go into field, and why it is not caught up in unit test and regression test.
Whether our unit test and regression test should be improved?

Client/server mismatch is a very common problem, in development we should think whether our change would cause client/server mismatch, if yes, do unit test carefully for all possible combinations, old client/new server, new client/old server, new client/new server.
And always run regression test for all possible combinations.

Software Usability Issue Part 2

Software Usability Issue Part 2 - Forgotten Password

Today, I want to buy some items in So I started to register one account, and entered the user name, and email. After I submitted the form, it prompts that 'the email is already occupied'. At that time, I realized that I already registered on this site a long, long time ago, but I had totally forgot the password. As many other sites, it provide the link to recover the password.

    But this is what I dislike. In the 'password recovery' page, it asks me for email, user name, and image verification code.
    Darn, I can't remember the user name at all, and even why I should enter the user name? Is the email not enough to recover password? Or at least it should provide me a way to get my user name, such as send the user name to my email. Also maybe the image verification code is not necessarily needed.

The common way to recover password:
    User just need enter the account's email, after that:
    1. The application would send him a email containing the link to reset password, and that link would be only valid in limited time (30 minutes or more), and can only be used once, it would be immediately invalid after user clicks it. This is the way I like.
    2. Send him a temporary password, user can use it to login to the site, and has to change his password with limited time. But using this solution, others can request application to change the account's password too, maybe just for a practical joke.
    3. Or simply just send his current password to him, but using this solution, the application must be able to get user's password in clear-text - it has to store password in clear-text, or use encryption algorithms that is able to decrypt original password from cipher-text.


Java (162) Lucene-Solr (112) Interview (63) J2SE (53) Algorithm (45) Soft Skills (39) Eclipse (32) Code Example (31) Troubleshooting (27) JavaScript (23) Linux (22) Spring (22) Tools (22) Windows (22) Web Development (20) Nutch2 (18) Bugs (17) Dev Tips (17) Debug (16) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (10) Problem Solving (10) Google (9) How to (9) Learning code (9) Performance (9) Security (9) UIMA (9) html (9) Design (8) Http Client (8) Maven (8) bat (8) blogger (8) Big Data (7) Database (7) Guava (7) JSON (7) Shell (7) System Design (7) ANT (6) Coding Skills (6) Lesson Learned (6) Programmer Skills (6) Scala (6) css (6) Algorithm Series (5) Cache (5) Continuous Integration (5) IDE (5) Testing (5) adsense (5) xml (5) AIX (4) Become a Better You (4) Code Quality (4) Concurrency (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Life (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Review (4) Spark (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Distributed (3) Dynamic Languages (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Mac (3) Python (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) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Fiddler (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Logging (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Firefox (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) Invest (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (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) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Tips (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts