Programmer's Blog

Programmer's reference

Category Archives: Java

[java] thread pool example

public class ThreadPool implements Runnable{
   private final LinkedBlockingQueue\<Runnable\> queue;
   private final List\<Thread\> threads;
   private boolean shutdown;

public ThreadPool(int numberOfThreads) {
   queue = new LinkedBlockingQueue\<\>();
   threads = new ArrayList<>();

for (int i=0; i\<numberOfThreads; i++) {
   Thread thread = new Thread(this);
   thread.start();
   threads.add(thread);
   }
}

public void execute(Runnable task) throws InterruptedException {
   queue.put(task);
}

private Runnable consume() throws InterruptedException {
   return queue.take();
}

public void run() {
   try {
       while (!shutdown) {
         Runnable task = this.consume();
         task.run();
       }
   } catch(InterruptedException e) {
 }
   System.out.println(Thread.currentThread().getName() + " shutdown");
 }

public void shutdown() {
   shutdown = true;

   threads.forEach((thread) -\> {
   thread.interrupt();
   });
}

public static void main(String[] args) throws InterruptedException {
    ThreadPool threadPool = new ThreadPool(5);
    Random random = new Random();

    for (int i=0; i\<10; i++) {
        int fi = i;
        threadPool.execute(() -\> {
          try {
             Thread.sleep(random.nextInt(1000));
             System.out.printf("task %d complete\n", fi);
          } catch (InterruptedException e) {
             e.printStackTrace();
          }
        });
    }

    Thread.sleep(3000);
    threadPool.shutdown();
}
}

[java] virtual functions

source: http://stackoverflow.com/questions/16617291/abstract-virtual-functions-in-java

As I mentioned in my comment private functions are not virtual and I want to demonstrate it using following example:

class A {
    public void foo() {
        System.out.println("A#foo()");
    }

    public void bar() {
        System.out.println("A#bar()");
        qux();
    }

    private void qux() {
        System.out.println("A#qux()");
    }
}

class B extends A {
    public void foo() {
        System.out.println("B#foo()");
    }

    private void qux() {
        System.out.println("B#qux()");
    }
}

Now lets run following code:

A foobar = new B();
foobar.foo(); // outputs B#foo() because foobar is instance of B
foobar.bar(); // outputs A#bar() and A#qux() because B does not have method bar 
              // and qux is not virtual

[Java] Simple thread-safe singleton class

public class threadSafeSingleton {

  //objects in singleton
  private HashMap<String, String> myHashMap = new HashMap<String, String>();
  private static threadSafeSingleton singletonInstance = null;

  protected threadSafeSingleton() {
  }
  
  public static threadSafeSingleton getSingleton() {
    if (singletonInstance == null) {
      singletonInstance = new threadSafeSingleton();
    }
    return singletonInstance;
  }

}

[Java] Semaphore example

ExecutorService executor = Executors.newFixedThreadPool(10);

Semaphore semaphore = new Semaphore(5);

Runnable longRunningTask = () -> {
  boolean permit = false;
  try {
     permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
     if (permit) {
       System.out.println("Semaphore acquired");
       sleep(5);
     } else {
       System.out.println("Could not acquire semaphore");
     }
  } catch (InterruptedException e) {
    throw new IllegalStateException(e);
  } finally {
    if (permit) {
      semaphore.release();
    }
  }
}

IntStream.range(0, 10)
 .forEach(i -> executor.submit(longRunningTask));

stop(executor);

[Java] Runnable notify and wait

1. implements Runnable
2. implement the run method

public void run() {
  synchronized(this) {
     <do something here>
     notify();
  }

public void main() {
  Thread t1 = new Thread(this);
  t1.start();

  <do something there>

   synchronized(t1) {
     try {
       System.out.println("Waiting for the other thread to complete");
             t1.wait(); 
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
    }

}



}

[Java] Multiple Hash map for hierarchical data

import java.util.*;
import java.lang.*;
import java.io.*;

class myClass
{
 public static void main (String[] args) throws java.lang.Exception
 {
 
 HashMap<Integer, String> inHash = new HashMap<Integer, String>();
 HashMap<Integer, HashMap<Integer, String>> myHash = new HashMap<Integer, HashMap<Integer, String>>();

 inHash.put(1,"Hello");
 myHash.put(1,inHash);
 
 System.out.println(myHash.get(1).get(1));
 }
}

[JDBC] Prepared Statement with HashMap Example

//for demonstration, try catch phrases are removed

public void updateCoffeeSales(HashMap<String, Integer> salesForWeek) {

    PreparedStatement updateSales = null;
    String updateString = "update " + dbName + ".COFFEES " +
                          "set SALES = ? where COF_NAME = ?";

    con.setAutoCommit(false);    //con is java.sql.jdbc.Connection
    updateSales = con.prepareStatement(updateString);

    //Map fields <COF_NAME, SALES>
    for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
            updateSales.setInt(1, e.getValue().intValue());  //SALES
            updateSales.setString(2, e.getKey());   //COF_NAME
            updateSales.executeUpdate();
            con.commit();
     }

     if (updateSales != null) {
          updateSales.close();
     }
     con.setAutoCommit(true);
}

[JDBC] Simple Query Statement

Complete Example for simple statement, note that it is using com.mysql.jdbc Connections from mysql-connector-java (Connector/J)

Configuring class path in windows if you install using a MSI, use the following path:

C:\Progra~2\MySQL\MySQL~1  , where Progra~2 refers to Program Files (x86)

package com.testing.testing;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.jdbc.Statement;
import com.mysql.jdbc.Connection;

public class Testing {
    
        public void getData() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {

            Class.forName("com.mysql.jdbc.Driver");
            
            com.mysql.jdbc.Connection conn = null;
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "user", "passwd");
                
            System.out.println("Connected to database");

            //Begin Statement---------------------------------
            Statement stmt = (Statement) conn.createStatement();
            String query = " Select * from mytable";
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next()) {
                
                int id = rs.getInt("ID");
                String name = rs.getString("NAME");
                System.out.println("Record: " + id + " " + name);
            }            
           //End Statement---------------------------------
           conn.close();
}

        public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            
            Testing mytest = new Testing();
            try {        
                mytest.getData();
            } catch (Exception e) 
            {
                System.out.println("SQL ERROR!");
                e.printStackTrace();
            }
        }
}

[JDBC] Connection to MySQL

//mysql-connector-java library is needed
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.jdbc.Statement;
import com.mysql.jdbc.Connection;
public class myclass{

    public Connection getConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            com.mysql.jdbc.Connection conn = null;
         
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname", "user", "passwd");
                
            System.out.println("Connected to database");
            return conn;
        }
    ...
    ... conn.close();
}


/* For setting parametered login, use Properties object

            Properties connectionProps = new Properties();
            connectionProps.put("user", varUser);
            connectionProps.put("password", varPasswd);
            ...
            conn = (Connection) DriverManager.getConnection(varURL, connectionProps);

*/

[Java] Set thread priority

Create Thread object and use setPriority method to rise the value of NORM_PRIORITY parameter

Thread thrd1 = new Thread("High");
Thread thrd2 = new Thread("Low");

thrd1.setPriority(Thread.NORM_PRIORITY+2);
thrd2.setPriority(Thread.NORM_PRIORITY-2);