Wednesday, January 30, 2019

A shortcut to check if a table has a column

If you want to check if the table PRODUCT has an ENGINEER field, you can execute the SQL below.

select ENGINEER from PRODUCT where 1=0;

If the column does not exist, it will give such an error message

ERROR at line 1:
ORA-00904: "ENGINEER": invalid identifier

else it will put out

no rows selected

  -----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live


 

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Friday, January 25, 2019

Read and write / modify a map simultaneously / concurrently with multiple Threads

When there are multiple threads modify and read a map at the same time, it can mess up the data and result in retrieving wrong information. There are several ways to solve this problem.

A. Atomic Access

This approach takes advantage of that reassigning a reference variable is atomic.

public class AtomicMapAccess {
      private HashMap<String, Integer> theMap = new HashMap<>();

      public void readMap() {
            //The localReadMap will not be affected if a new map is assigned to theMap
            //This step is atomic
            HashMap<String, Integer> localReadMap = theMap;
            Set<String> keys = localReadMap.keySet();

            for (String key : keys) {
                  System.println(localReadMap.get(key));
            }
      }

      public void modifyMap() {
            //Create a new instance of map to take all the new set of data
            HashMap<String, String> localModifyMap = new HashMap<>();
         
            Random rand = new Random();
            localModifyMap.put("key1", rand.nextInt());
            localModifyMap.put("key2", rand.nextInt());
            localModifyMap.put("key3", rand.nextInt());

            //An atomic step to assign the map with new data to theMap.
            theMap = localModifyMap;
      }

      public class writer implements Runnable {
            public void run() {
                         modifyMap();
                 
                          try {
                                Thread.sleep(20);
                          }catch(InterruptedException e) {
                                 e.printStackTrace();
                          }
             }
      }

      public class reader implements Runnable {
            public void run() {
                         readMap();
                 
                          try {
                                Thread.sleep(20);
                          }catch(InterruptedException e) {
                                 e.printStackTrace();
                          }
             }
      }

      public static void main(String[] args) {
            Thead[] writers = new Thread[3];
            for (int i=0; i<writers.length; i++) {
                  writers[i] = new Thread(newWriter());
                  writers[i].start();
                  writers[i].join();
            }

            Thread[10] readers = new Thread[10];
             for (int j=0; i<readers.length; j++) {
                   readers[j] = new Thread(new Reader());
                   readers[j].start();
                   readers[j].join();
             }
      }
}

This approach works fine if the size of the map is not very huge, for each time a thread modifies the map, it needs to reassign data from all the slots to the newly created map, which could be time consuming if the map is huge.

B. ConcurrentHashMap

ConcurrentHashMap<String, Integer>  theMap = new ConcurrentHashMap<>();

With the ConcurrentHashMap, update is done with a lock at the hashmap basket level, so that is uses multiple locks. However, iterators are designed to be used by one Thread at a time.

C. Synchronized HashMap

Map<String, Integer> theMap = Collections.synchronizedMap(new HashMap<<>());

This approach guarantees serial access, It locks at the map level, which is less efficient. Furthermore, when navigating through the map with Iterators, it is imperative to do it in a synchronized block on the map.

Set<String> keys = theMap.keySet();
synchronized(theMap) {
      for(String key : keys) {
           Integer value = theMap.get(key);
      }
}

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live


     

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.


Friday, January 18, 2019

try-with-resource vs. try-catch-finally

The try-with-resource was introduced to java in JDK1.7. While both try-with-resource and the finally blocks guarantee to close the resources, the differences between them are subtle.  

1. try-catch-finally

public void copyA(String source, String destination) throws FileNotFoundException, IOException {
      BufferedReader reader = null;
      PrintWriter writer = null;
      try {
            reader = new BufferedReader(new FileReader("source"));
            writer = new PrintWriter(new BufferedWriter(new FileWriter("destination")));

            String line = null;
            while((line = reader.readLine()) != null) {
                  writer.printLine(line);
             }
            writer.flush();
      } finally {
            if (reader != null) reader.close();
            if (writer != null) writer.close();
      }
}

 
2. try-with-resource

public void copyB(String source, String destination) throws FileNotFoundException, IOException {
      try (BufferedReader reader = new BufferedReader(new FileReader("source"));
                  PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("destination")))){
            String line = null;
            while((line = reader.readLine()) != null) {
                  writer.printLine(line);
             }
            writer.flush();
}

Both copyA and copyB will close the reader and writer either the code is executed successfully or throws exceptions.

If an exception occurs in the try block, with try-with-resource, method copyB will always throw the original exception from the try block. With the try-finally block, if the reader and writer are closed successfully without error, method copyA will also throw the original exception from the try block. However, if either the reader or the writer failed to close and throws IOException, copyA will throw the IOException from the finally block instead the one from the try block, which is known as EXCEPTION MASKING.

One way to avoid exception masking is to handle the exceptions within the method by catching them.

public void copyA(String source, String destination) throws FileNotFoundException, IOException {
      BufferedReader reader = null;
      PrintWriter writer = null;
      try {
            reader = new BufferedReader(new FileReader("source"));
            writer = new PrintWriter(new BufferedWriter(new FileWriter("destination")));

            String line = null;
            while((line = reader.readLine()) != null) {
                  writer.printLine(line);
             }
            writer.flush();
      } catch (FileNotFoundException fe) {
            fe.printStackTrace(System.out);
      } catch(IOExcetpion ie) {
            ie.printStackTrace(System.out);
      } finally {
            try {
                 if (reader != null) reader.close();
                 if (writer != null) writer.close();
            } catch(IOExcetpion ioe) {
                  ioe.printStackTrace(System.out);
            }
      }
}


public void copyB(String source, String destination) throws FileNotFoundException, IOException {
      try (BufferedReader reader = new BufferedReader(new FileReader("source"));
                  PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("destination")))){
            String line = null;
            while((line = reader.readLine()) != null) {
                  writer.printLine(line);
             }
            writer.flush();
} catch (FileNotFoundException fe) {
      fe.printStackTrace(System.out);
} catch(IOExcetpion ie) {
      ie.printStackTrace(System.out);
}

Now, all the exceptions from all the blocks will be printed to your output. However, method copyA will handle the exception from the try block before the reader and writer are closed, and copyB will handle the exception after the reader and writer are closed.

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live


       

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Reference:

1.The try-with-resources Statement

Thursday, January 17, 2019

Solved - Change the data type of a column which has already had data; ORA-01439: column to be modified must be empty to change datatype

Lets say you have a column, Level, in your Product table. The original data type of the column is Varchar. Now, you want to change the data type to Number.

If you simply use "ALTER TABLE Product MODIFY Level NUMBER", you will have the following error.

ORA-01439: column to be modified must be empty to change datatype

To work around this problem, following the following steps.

1. Add a temporary column to the Product table with the required new data type.

           ALTER TABLE Product ADD Level_temp NUMBER;

2. Use your data conversion logic, convert the data in column Level to NUMBER and add that value to the corresponding Level_temp column.

          UPDATE Product SET Level_temp = <the converted value> where Level = <original value>;

           If you don't need to convert the data, you can do the following.
           UPDATE Product SET Level_temp = Level;

3. Drop the Level column.

          ALTER TABLE Product DROP COLUMN Level;

4. Rename the Level_temp to Level.

          ALTER TABLE Product RENAME COLUMN Level_temp TO Level;

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live


         

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.