Thread in Java.

1. What is Thread?
 1.a. Thread is a Light-weight ,its allow multiple activities within a single process.
 1.b. All treads of a process share the common memory space, The process of execution multiple threads simultaneously is known as multi-threading.

2. Non-Thread Program vs Thread Program

2.a. Example Non-Thread Program.

public class WithoutThread {

 // main method
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String str = “banana”;
  String str2 = “papaya”;
  ProcessClass proStr = new ProcessClass();
class ProcessClass{
 public void IterateRandomValue(String itr){
  for (int i = 0; i < 5; i++) {
    System.out.println(i + ” ” + itr );

OUTPUT in Console:
0 banana
1 banana
2 banana
3 banana
4 banana
0 papaya
1 papaya
2 papaya
3 papaya
4 papaya

Descriptions on without Thread class : without added thread class, it will execute the process one by one ( check the output program above, program banana will run first until its finish, and then, papaya program will be run ) – sequentially. the Process will taking longer time to finish the processing compare than extends Thread class or implements Runnable class.

2.b. Thread Program.

  • the Functions of Java Threads is to allow multiple activities within a single process.
  • To implement The Threads function we need to extends Thread Class or Implements Interface Runnable Class.

Example Program extend Thread class.

public class ThreadExample {
 //Main Thread
    public static void main(String[] args)
     // TODO Auto-generated method stub
     String str = “banana”;
     String str2 = “papaya”;
     // First Thread
     ExtendThread firstThread = new ExtendThread(str);
        //Second Tread
     ExtendThread secondThread = new ExtendThread(str2);


class ExtendThread extends Thread
 private String strNew;

 ExtendThread(String str) {
  strNew = new String(str);

 public void run() {
  for (int i = 0; i < 5; i++) {
   System.out.println(i + ” ” + strNew);


Starting Banana
Creating ..Papaya
Starting Papaya
Thread : Banana,4
Thread : Papaya,4
Thread : Banana,3
Thread : Papaya,3
Thread : Banana,2
Thread : Papaya,2
Thread : Banana,1
Thread : Papaya,1

  • If we see the results for (papaya,1) and (Banana, 1) its actually run simultaneously
  • How to Use ServletOutputStream – for Servlet Download zip file into response Client?

    Good Day!

    How to Use ServletOutputStream – for Servlet Download zip file into response Client?

    Description / Answer:

    • from the lib descriptions – Provides an output stream for sending binary data to the client.
    • is an abstract class that the servlet container implements. Subclasses of this class must implement the method.
    • method that are regularly used are : .write() – writing what the client request and paste to servlet response client.
    • Its use to attached the Output Stream to download on browser.

    example program – Servlet Class :

    ServletOutputStream servletOutputStream = null;
    FileInputStream fileInputStream = null;
    filename = “documentInput.Zip“;

    try {
    File file = new File(“C://documents/temp/“);
    fileInputStream = new FileInputStream(file);
    servletOutputStream = response.getOutputStream();

    // download using browser client – change to byte
    response.addHeader(“Content-Disposition“,”attachment;filename=\“” + filename + “\””);
    byte[] arBytes = new byte[32768];

    int count;
    while ((count = > 0)
    servletOutputStream.write(arBytes, 0, count);

    }catch (IException e) {
    // TODO: handle exception
    } finally{

    Creating example jax-ws Service Provider + ejb 3.1 + mysql + webSphere v7.0 + RAD v 8.0.2- part 2

    Creating example jax-ws Service Provider + ejb 3.1 + mysql + webSphere v7.0 – part 2

    1.) Create EAR file, at your Rational Application Development – RAD, right click  select New > Enterprise Application Project > Project name : “studEAR” > Finish


    2.) Create new Project EJB. New > Other > Java EE > Utility Project > Next > Project Name “studentEJB” >  Finish






    Create Simple Web Service JAX-WS – Client Part – RAD IBM – Websphere 7.0 + java 6

    Create Simple Web Service JAX-WS – Client Part – RAD IBM – Websphere 7.0 + java 6

    1.) After you done doing my example on JAX-WS Server Part 1, you can create new Dynamic web project “jaxwsClientFirst” – for client part.

    1.1.) Create package, com.fndong.client, then right click New > others > Web Service > Web Service Client


    1.2.) Create package, com.fndong.client, then right click New > others > Web Service > Web Service Client.


    Click on Browse Button of Service Definition and select the WSDL file of jaxwsServerFirst , Press Ok. Then set the target Location “com.fndong.client” > Next > Finish.

    1.3.) Then it will generated java class automatically :


    1.4.) Open class , inside the codes, change the URL to  :

    url = com.fndong.client.SalaryImplService.class.getResource(“/WEB-INF/wsdl/SalaryImplService.wsdl”);


    url = com.fndong.client.SalaryImplService.class.getResource(“http://localhost:9080/jaxwsServerFirst/SalaryImplService/SalaryImplService.wsdl&#8221;);

    1.5.) This client jax-ws used WebSphere thin client jar for WebService Client. Right Click on jaxwsClientFirst  >BuildPath > Configure Build Path,Under Libraries Tab ->


    Click on WebSphere Application Server v7.0. Click On Remove, and Press OK.

    1.6.) Then add thin client jar , Right Click again on jaxwsClientFirst  >BuildPath > Configure Build Path,Under Libraries Tab ->  Add External JARs > add three jars below.


    – click OK Button.

    1.7.) Create a client program that invokes the server jaxwsServerFirst, by Creating new Client java class in the package com.fndong.client – ““.

     package com.fndong.client;
     * @author fndong
    public class CalculateClient {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
             SalaryImplService service = new  SalaryImplService();
             SalaryService salaryService = service.getSalaryImplPort();
             double var1 = 2000;
             double var2 = 5000;
             double mysalary = salaryService.calculateSalaryAllowance(var1, var2);
             System.out.println("my salary : " + mysalary);       


    Create Simple Web Service JAX-WS – Server Part – RAD IBM – Websphere 7.0 + java 6

    1). Create Simple Web Service JAX-WS – RAD IBM – Websphere 7.0 + java 6

    1.1) Create your ear File first – Select New > Enterprise Application Project – “jaxwsServerEar” – Server Web Service  Part  1

    1.2.) Create New Java Project – Select New > Dynamic Web Project– “jaxwsServerFirst


    1.3) create your Interface class with package. Create Package – com.fndong.service  / create your Class web Service “SalaryService” ( The interface will list calculate the salary and allowance)

    package com.fndong.service;
    import javax.jws.WebMethod;
    import javax.jws.WebService;
     * @author fndong
    public interface SalaryService {
         public int calculateSalaryAllowance(double salary, double allowance);
    • The @WebService annotation marks the WebServiceFirst class as implementing a web service, which results in a deployable web service being produced.
    • The @WebMethod

    1.4.) Create implementation class to calculate Salary and Allowance – “SalaryImpl

    package com.fndong.Impl;
    import com.fndong.service.SalaryService;
     * @author fndong
    public class SalaryImpl implements SalaryService {
        public double calculateSalaryAllowance(double salary, double allowance) {
             return salary + allowance;

    1.5.) Create Web Service for the Implementation Class “SalaryImp” by right SalaryImp > Web Services> create WebServices


    • Next > check the box – Generate WSDL file into the project.













    Next > Next > Finish

    1.6.) The Class “” will generated automatically and also WSDL files. ( Check inside WebContent Folder)


    1.7.) The server started and test the result and also validate the WSDL.


    1.7.1.) check the WSDL document in the browser.



    1.8.) Test with WebServices Explorer, just right click wsdl->WebServices->Test with WebServices Explorer


    1.9.) It will load the page in your RAD . You test the result of calculation between Salary and Allowance, for arg0 = 3000 and arg1 = 50 , Click Go Button, so the result at the Status – Body:


    Selamat Mencuba (malay languange)

    notes for programming – mixed – Q & A – Part 1

    Notes for programming – mixed – Q & A – Part 1

    1.) What is difference between extends and implementations in java (20/09/2016) ?


    1.1.a) extends is for extending a class.
    1.1.b) implements is for implementing an interface

    Difference Between Implements and Extends

    2.) which is the best practice for checking condition if the Object is null (21/09/2016)?

    – Lets say you want to checking if your object input are null, there are three ways:
    1) Add null first to check the input
    CORRECT – The best practice

    2) Add input first then check with null

    INCORECT – not the best practice , WHY ? – it will potentially causing a NullPointerException.

    3) check the condition by == this syntax equals
    if(input == null)  

    CORRECT – The best practice

    3.) what is best practice for Java String method (local) variables be initialized to null or “”?

    • its depends on what your programs want to do, there are certain time we need to initialized or directly set to null because we want to check the condition input != null and do something, but if we wanted to prevent the nullpointer its better to set “” – EMPTY string. 

    4.) Missing braces in If statement is not recommendation.

    4.1. First codes without curly braces:

        do this;
        do this;

    4.2. Second codes with curly braces:

        do this;
        do this;
    • if the First and the second is the best if-else recommendation.
      • answers: when not Omitting braces it will harms readability and can easily cause issues when the code is modified.
      • for the first if statement , the compiler will read for the first do this.
      • Code merges. It’s been known to happen on projects I’ve worked on that single-statement ifs have been broken by automatic merges. The scary thing is the indentation looks right even though the code is wrong, so this type of bug is hard to spot.So I go with braces – on their own lines. It’s easier to spot the levels that way. Yes, it does waste vertical screen real estate and that’s a genuine downside. On balance though, I think it’s worth it.
      • if really don’t want to use curly braces, write just one line only, its really safeful:
        • if (condition) dothis();

    5.) Date date = new Date(); date.parse(“String_date_format“) , does no longer supported, Deprecated. .parse() :

    • With Java 8, the preferred date/time classes are no longer in the java.util package and the preferred date/time handling classes are now in the java.time package.
    • The DateTimeFormatter class provides of Pattern methods to provide an instance of DateTimeFormatter based on the provided date/time pattern String. One of the format methods can then be called on that instance of DateTimeFormatter to get the date and/or time information formatted as a String matching the provided pattern.

    5.1.) DEPRECATED
    java.util.Date date = new java.util.Date();
    java.text.SimpleDateFormat dateformat = new java.text.SimpleDateFormat(“YYYY-dd-MM”);
    date.parse(date.parse()); // The method parse(String) from the type Date is deprecated

    5.2) NEW Date Format for Java 8
    – using: java.time.LocaleDate();

     LocalDate date =;
      String text = date.format(formatter);
      LocalDate parsedDate = LocalDate.parse(text, formatter);

    5.3.) How to passing value Date with Format Pattern – “YYYY-dd-MM” to save to database? (29/09/2016 – 11.00 am – HTV Building)

    LocalDate localDate =; // YYYY-mm-dd - java.time 8
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // java.time 8
    SimpleDateFormat smpdatef = new SimpleDateFormat("yyyy-MM-dd"); // java.text
    String strldate = localDate.format(formatter);
    Date date  = smpdatef.parse(strldate);
    // using sql date to change to Date 
        java.sql.Date datesql = null;
    datesql = new java.sql.Date(smpdatef.parse(strldate).getTime());
    System.out.println("date sql : " + datesql);
    // set to entity with Date value
    Users user = new Users();

    Output: date sql : 2016-09-29

    6.) Operator: what is super() method in java? (4/10/2016)

    1.1. Super keyword are to use for accessing Superclass’s Member and reference variable is used to refer parent class Object.
    1.2. the Subclass method overrides one of its superclass’s methods, it can invoke the overridden method through the use for keyword super.

    a. At variable level.
    b. At method level.
    c. At constructor level.


    How to generate age from date of Birth – (Java 8) – java.time.*

    How to generate age from date of Birth – Java 8 – java.time.*

    package unit.test.timejava8;
    import java.time.LocalDate;
    import java.time.Period;
     * @author fndong
     * generate age from date of Birth Java 8 - java.time.*
    public class Java8TimeAge {
        public void getAge(){
          String dob = "1989-07-20";
         LocalDate localDate = LocalDate.parse(dob);
         LocalDate now =;
         Period  period = Period.between(localDate,now);
            System.out.printf("%d years,%d months and %d days  old!\n",p.getYears(), p.getMonths(), p.getDays());
        public static void main(String args[]){
            Java8TimeAge java8TimeAge = new Java8TimeAge();

    Output :

    32 years,1 months and 2 days  old!


    vaadin – How to add try catch exception inside addValueChangeListener with lambda expression

    Good Day !

    Title : Vaadin – How to add try catch exception inside addValueChangeListener with lambda expression (java 8)

    Example :

    // add lambda expression – java 8
    (ValueChangeEvent) -> {
               try {
    objectsDistrict.addAll(findDistrictSelection((RefState)                                        ValueChangeEvent.getProperty().getValue()));
       } catch (Exception e) {
     // TODO: handle exception

                    “Error on Selection Records“,

    2) The Above codes are from Source code tutorial – vaadin – How to create a second Combobox which is dependent from the First Combobox.

    Java Versions

    java versions :

    1.) JDK Version 1.0

    • Applet are the Big things.
    • 250 Classes

    2.) JDK Version 1.1

    • More capable , friendlier, becoming very popular, Better GUI code.
    • 500 Classes

    3.) J2SE Version 1.2 (java 2 – 1.2 to 1.4)

    • Comes in three flavours: Micro Edition (J2ME), Standard Edition (J2SE), and Enterprise Edition (J2EE).
    • Becomes the language of choice for new enterprise (especially web-based) and mobile applications.
    • 2300 Classes

    4.) J2SE Version 5.0 (version 1.5)

    • More power, and easier to develop with thousand additional classes.
    • 3500 classes
    • Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities
    • Autoboxing/unboxing: automatic conversions between primitive types.
    • Enumerations: the enum keyword creates a typesafe, ordered list of values.
    • Varargs: the last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)); in the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.
    • Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes


    5.) Java Version SE 6

    • performance improvements for the core platform, and Swing.
    • Improved Web Service support through JAX-WS.
    • JDBC 4.0 support.
    • Java Compiler API, an API allowing a Java program to select and invoke a Java Compiler programmatically.
    • Many GUI improvements, such as integration of SwingWorker in the API, table sorting and filtering, and true Swing double-buffering (eliminating the gray-area effect).
    • JVM improvements include: synchronization and compiler performance optimizations, new algorithms and upgrades to existing garbage collection algorithms, and application start-up performance.

    6.) Java Version SE 7

    7.) Java Version SE 8

    • Language-level support for lambda expressions (officially, lambda expressions; unofficially, closures) under Project Lambda.
    • Repeating annotations
    • Date and Time API
    • Launch JavaFX applications (direct launching of JavaFX application JARs)
    • Annotation on Java Types
    1. More info on java versions , features and History : GO HERE
    2. Wikipedia about History on Java Versions.