Wednesday, 18 December 2019

How to create thread pool executor in java

package kp;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class MyPooledThread extends Thread {

private BlockingQueue<Runnable> taskQueue = null;
private boolean isStopped = false;
CountDownLatch latch = null;

public MyPooledThread(BlockingQueue<Runnable> queue, CountDownLatch latch) {
taskQueue = queue;
this.latch = latch;
}

@Override
public void run() {
while (!isStopped()) {
try {
Runnable runnable = taskQueue.poll(5, TimeUnit.SECONDS);
if(runnable != null){
runnable.run();
doStop();
}
latch.countDown();
System.out.println("count down");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public synchronized void doStop() {
this.isStopped = true;
//this.interrupt();
}

public synchronized boolean isStopped() {
return isStopped;
}
}



-----------------------------------------------------------------------------------------------------------------


package kp;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

public class  MyThreadPoolExecuter {

BlockingQueue<Runnable> queue = null;
List<Thread> threads = new ArrayList<Thread>();
CountDownLatch latch = null;
private boolean isStopped = false;

public MyThreadPoolExecuter(int noOfThreads, BlockingQueue<Runnable> queue, CountDownLatch latch) {
this.queue = queue;
this.latch = latch;

for (int i = 0; i < noOfThreads; i++) {
Thread t = new MyPooledThread(this.queue, latch);
threads.add(t);
t.start();
}
}

public synchronized void execute(Runnable r) {
if (this.isStopped) {
new IllegalStateException("Threadpool is stopped");
}
try {
queue.put(r);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public synchronized void stop() {
this.isStopped = true;
for (Thread thread : threads) {
((MyPooledThread)thread).doStop();
}
}
}


---------------------------------------------------------------------------------------------------------------------

package kp;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;

public class MyThreadPoolExecuterTestDrive {

public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(4);
MyThreadPoolExecuter executer = new MyThreadPoolExecuter(4,new ArrayBlockingQueue<Runnable>(4), latch);
executer.execute(()->{
System.out.println("I am thread 1");
});
executer.execute(()->{
System.out.println("I am thread 2");
});
executer.execute(()->{
System.out.println("I am thread 3");
});
executer.execute(()->{
System.out.println("I am thread 4");
});
executer.execute(()->{
System.out.println("I am thread 5");
});
try {
latch.await();
//executer.stop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

Custom ConcurrentHashMap Implementation in java

package kp;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class MyConcurrentHashMap<K, V> extends HashMap<K, V> {

private static final long serialVersionUID = 1L;

private ReentrantReadWriteLock[] lock = new ReentrantReadWriteLock[16];

public MyConcurrentHashMap() {
super();

for (int i = 0; i < 16; i++) {
lock[i] = new ReentrantReadWriteLock();
}

}

@Override
public V get(Object key) {

ReentrantReadWriteLock lock = getLock(key);
WriteLock wl = lock.writeLock();

if (lock.isWriteLocked()) {
try {
wl.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

lock.readLock().lock();
V value = super.get(key);
lock.readLock().unlock();
return value;
}

@Override
public V put(K key, V value) {

ReentrantReadWriteLock lock = getLock(key);
while (lock.getReadLockCount() > 0) {
try {
lock.readLock().wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lock.writeLock().lock();
V val = super.put(key, value);
lock.writeLock().unlock();
return val;
}

private ReentrantReadWriteLock getLock(Object key) {
int hash = hashCode(key);
return lock[hash / 100];
}

private int hashCode(Object key) {

return (key == null ? 0 : key.hashCode() % 1600);
}

}

------------------------------------------------------------------------------------------------------------------

package kp;

public class MyConcurrentHashMapTestDrive {

public static void main(String[] args) {

MyConcurrentHashMap<Integer, String> myConcurrentHashMap = new MyConcurrentHashMap<Integer, String>();
WriteMap w1 = new WriteMap(myConcurrentHashMap);
WriteMap w2 = new WriteMap(myConcurrentHashMap);
ReadMap r1 = new ReadMap(myConcurrentHashMap);
w1.setName("First Thread");
w2.setName("Second Thread");
w1.start();
w2.start();
r1.start();

}

}

class WriteMap extends Thread {
MyConcurrentHashMap<Integer, String> cMap;
public WriteMap(MyConcurrentHashMap<Integer, String> cMap){
this.cMap = cMap;
}
public void run(){
int i=1;
while(true){
cMap.put(i, this.currentThread().getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

class ReadMap extends Thread {
MyConcurrentHashMap<Integer, String> cMap;
public ReadMap(MyConcurrentHashMap<Integer, String> cMap){
this.cMap = cMap;
}
public void run(){
int i=1;
while(true){
System.out.println(cMap.get(i));
}
}
}





BlockingQueue Implementaion in java

package kp;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueExample {

public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);
     Producer producer = new Producer(queue);
     Consumer consumer = new Consumer(queue);
     new Thread(producer).start();
     new Thread(consumer).start();
     Thread.sleep(4000);
}
}

class Producer implements Runnable{

BlockingQueue< String> q=null;
public Producer(BlockingQueue<String> queue) {
this.q=queue;
}
public void run() {
try{
q.put("1");
Thread.sleep(1000);
q.put("2");
Thread.sleep(1000);
q.put("3");
Thread.sleep(1000);
q.put("4");
}
catch (Exception e) {
e.printStackTrace();
}
}

}

class Consumer implements Runnable {

BlockingQueue<String> queue=null;

public Consumer(BlockingQueue< String> b) {
this.queue=b;
}
public void run() {
try {
for (String string : queue) {
System.out.println(queue.take());
}
         

}
catch (Exception e) {
e.printStackTrace();
}
}
}

LRU Implementation in Java

package kp;

import java.util.LinkedHashMap;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private int size;

public LRUCache(int size) {
super(size, 0.75f, true);
this.size = size;
}

@Override
protected boolean removeEldestEntry(java.util.Map.Entry<K, V> paramEntry) {
return size() > size;
}

public static void main(String args[]) {

LRUCache<String, String> lruCache = new LRUCache<String, String>(7);

lruCache.put("2", "2");
lruCache.put("1", "1");
lruCache.put("3", "3");
lruCache.put("4", "4");
lruCache.put("5", "5");
lruCache.put("6", "6");
lruCache.put("7", "7");



//System.out.println("---" + lruCache.get("1"));
//System.out.println("---" + lruCache.get("2"));
//System.out.println("---" + lruCache.get("3"));

System.out.println(lruCache);
}

}

How to print hello world sequentially using thread in java.

package kp;

public class HelloWorldByWaitNotify {

public static void main(String[] args) {
Object o = new Object();
World worldObj = new World(o);
Hello hello = new Hello(worldObj);
Thread helloThread = new Thread(hello);
Thread worldThread = new Thread(worldObj);
helloThread.start();
worldThread.start();
Thread helloThread1 = new Thread(hello);
Thread worldThread1 = new Thread(worldObj);
helloThread1.start();
worldThread1.start();
}
}

class Hello implements Runnable {
World worldObj;

public Hello(World worldObj) {
this.worldObj = worldObj;
}

@Override
public void run() {
while (true) {
synchronized (worldObj) {
if (!this.worldObj.isWorld) {
System.out.println("Hello");
this.worldObj.isWorld = true;
worldObj.notify();
}
}
}
}
}

class World implements Runnable {
public boolean isWorld = false;
Object o;

public World(Object o) {
this.o = o;
}

@Override
public void run() {
while (true) {
synchronized (this) {
try {
if (!this.isWorld) {
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("WORLD!!!!!!");
this.isWorld = false;
}
}
}
}