0% found this document useful (0 votes)
54 views9 pages

Con Currency

1) The document discusses issues with using hashmaps in multithreaded applications and provides solutions using concurrent hashmaps. It also covers catching exceptions from threads and using different Executor types from the java.util.concurrency package including single thread, thread per task, fixed thread pool and cached thread pool executors. 2) It provides an example of problems that can occur with multiple threads putting data into a shared hashmap concurrently and shows how to resolve it by using a concurrent hashmap instead. 3) Exceptions thrown from threads are handled using the default uncaught exception handler and different Executor implementations are demonstrated including running tasks sequentially or distributing them across multiple threads.

Uploaded by

Tharani21
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views9 pages

Con Currency

1) The document discusses issues with using hashmaps in multithreaded applications and provides solutions using concurrent hashmaps. It also covers catching exceptions from threads and using different Executor types from the java.util.concurrency package including single thread, thread per task, fixed thread pool and cached thread pool executors. 2) It provides an example of problems that can occur with multiple threads putting data into a shared hashmap concurrently and shows how to resolve it by using a concurrent hashmap instead. 3) Exceptions thrown from threads are handled using the default uncaught exception handler and different Executor implementations are demonstrated including running tasks sequentially or distributing them across multiple threads.

Uploaded by

Tharani21
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

 

 
java.util.concurrency and multithreading 
 
 
1) Problems using hashmap in a multithreaded app. 
2) Using a concurrent hashmap 
 
3) Catching exceptions from threads 
 
4) Using Executor in java.util.concurrency
4.1) Single thread executor
4.2) Thread Per Task executor
4.3)Executors.newFixedThreadPool
4.3)Executors.newCachedThreadPool
 
1) Problems using HashMap 
 
Creates 20 threads that put strings into a shared hashmap. 
In the main thread concurrently iterate over the hashmap 
public class Hash {
HashMap<String, String> chm =
new HashMap<String, String>(16);

public static void main (String args []) {


new Hash();
}

public Hash(){
long start= System.currentTimeMillis();
for (int i= 0; i <20; ++i){
new Thread(
new Runner(chm,"t"+i,50)).start();
}
Iterator<String > keys= chm.keySet().iterator();

while(keys.hasNext()){
String key=keys.next();
System.out.println("MainThread: Key:" + key+
" and value:" + chm.get(key) );

}
long stop=System.currentTimeMillis();
long timeTaken = stop-start;
System.out.println("Time Taken is:"+ timeTaken);
}
}

class Runner implements Runnable{


HashMap<String , String> hm = null;
int count;
String message;

Runner(HashMap<String,String> hm, String message,


int count){
this.hm=hm;
this.count=count;
this.message = message;
}

public void run(){


for (int i=0; i< count; i++){
//key is threadname+i, value is message
hm.put(Thread.currentThread().getName()
+"-"+i, message);
}
}


MainThread: Key:Thread-0-21 and value:t0
MainThread: Key:Thread-2-13 and value:t2
MainThread: Key:Thread-5-35 and value:t5
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:841)
at java.util.HashMap$KeyIterator.next(HashMap.java:877)
at javait.concurrent.Hash.<init>(Hash.java:23)
at javait.concurrent.Hash.main(Hash.java:12)
2) Using concurrent Hashmap

Modify the above example to use a ConcurrentHashmap. 
 
 
package javait.concurrent;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/*
* Things to try:
* Read the api and modify the number from concurrencyLevel to suggest alternative
* sizing for partitioning
* change the number of threads and iterations.
*/
public class ConHash {

ConcurrentHashMap<String, String> chm =


new ConcurrentHashMap<String,String>(20);
//HashMap<String, String> chm = new HashMap<String, String>(16);

public static void main (String args []) {


new ConHash();
}

public ConHash(){
long start= System.currentTimeMillis();
for (int i= 0; i <20; ++i){
new Thread(new Runner(chm,"t"+i,50)).start();
}
Iterator<String > keys= chm.keySet().iterator();

while(keys.hasNext()){
String key=keys.next();
System.out.println("MainThread read Key:" + key
+ " and value:" + chm.get(key) );
}
long stop=System.currentTimeMillis();
long timeTaken = stop-start;
System.out.println("Time Taken is:"+ timeTaken);
}

}
class Runner implements Runnable{
ConcurrentHashMap<String , String> hm = null;
int count;
String message;

Runner(ConcurrentHashMap<String,String> hm, String message,


int count){
this.hm=hm;
this.count=count;
this.message = message;
}

public void run(){


for (int i=0; i< count; i++){
//System.out.println("--->"
+Thread.currentThread().getName());
hm.put(Thread.currentThread().getName()+"-"+i, message);
}
}


MainThread read Key:Thread-7-18 and value:t7
MainThread read Key:Thread-7-28 and value:t7
MainThread read Key:Thread-7-17 and value:t7
MainThread read Key:Thread-7-39 and value:t7
MainThread read Key:Thread-7-30 and value:t7
MainThread read Key:Thread-7-23 and value:t7
MainThread read Key:Thread-7-45 and value:t7
MainThread read Key:Thread-7-42 and value:t7
MainThread read Key:Thread-7-38 and value:t7
MainThread read Key:Thread-7-16 and value:t7
MainThread read Key:Thread-7-33 and value:t7
MainThread read Key:Thread-7-48 and value:t7
MainThread read Key:Thread-7-31 and value:t7
MainThread read Key:Thread-7-26 and value:t7
MainThread read Key:Thread-7-11 and value:t7
MainThread read Key:Thread-7-36 and value:t7
MainThread read Key:Thread-7-19 and value:t7
MainThread read Key:Thread-7-25 and value:t7
MainThread read Key:Thread-7-14 and value:t7
MainThread read Key:Thread-7-47 and value:t7
MainThread read Key:Thread-7-40 and value:t7
Time Taken is:78
3) Catching exceptions from threads

public class ThreadException {

static {
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e){
System.err.println(
"Thread caught by default handler="+ t.getName());
e.printStackTrace();

}
});
}

public static void main (String args []){


new Thread (new Runnable (){
public void run(){
ThreadException.dostuff();
}
}).start();

static void dostuff() {


throw new IllegalArgumentException("aaah");

}
4) Using Executor in java.util.concurrency
4.1) Single thread executor

import java.util.*;
import java.util.concurrent.*;

public class SingleExecuteHash {

Executor threadExecutor = new SingleThreadExecutor();


ConcurrentHashMap<String, String> chm =
new ConcurrentHashMap<String, String>(20);

public static void main (String args []) {


new SingleExecuteHash();
}

public SingleExecuteHash(){
long start= System.currentTimeMillis();
for (int i= 0; i <20; ++i){
threadExecutor.execute(new Runner(chm,"t"+i,50)); // no
start()!!!
}
Iterator<String > keys= chm.keySet().iterator();

while(keys.hasNext()){
String key=keys.next();
System.out.println("MainThread read Key:" + key+
" and value:" + chm.get(key) );

}
long stop=System.currentTimeMillis();
long timeTaken = stop-start;
System.out.println("Time Taken is:"+ timeTaken);
}
}

public class SingleThreadExecutor implements Executor{


public void execute( Runnable task ){
task.run();
}
}

All tasks run in the main thread:



MainThread read Key:main-31 and value:t19
MainThread read Key:main-27 and value:t19
MainThread read Key:main-17 and value:t19
MainThread read Key:main-28 and value:t19
MainThread read Key:main-39 and value:t19
MainThread read Key:main-34 and value:t19
MainThread read Key:main-42 and value:t19
Time Taken is:28
4.2) Thread Per Task executor

package javait.concurrent;

import java.util.*;
import java.util.concurrent.*;

public class ThreadPerTaskExecuteHash {

Executor threadExecutor = new ThreadPerTaskExecutor();


ConcurrentHashMap<String, String> chm =
new ConcurrentHashMap<String, String>(20);

public static void main (String args []) {


new ThreadPerTaskExecuteHash();
}

public ThreadPerTaskExecuteHash(){
long start= System.currentTimeMillis();
for (int i= 0; i <20; ++i){
threadExecutor.execute(new Runner(chm,"t"+i,50)); }
Iterator<String > keys= chm.keySet().iterator();

while(keys.hasNext()){
String key=keys.next();
System.out.println("MainThread read Key:" + key+
" and value:" + chm.get(key) );
}
long stop=System.currentTimeMillis();
long timeTaken = stop-start;
System.out.println("Time Taken is:"+ timeTaken);
}
}

public class ThreadPerTaskExecutor implements Executor{


public void execute( Runnable task ){
new Thread(task).start();
}
}

All tasks run in their own threads



MainThread read Key:Thread-7-36 and value:t7
MainThread read Key:Thread-7-19 and value:t7
MainThread read Key:Thread-7-25 and value:t7
MainThread read Key:Thread-7-14 and value:t7
MainThread read Key:Thread-7-47 and value:t7
MainThread read Key:Thread-7-40 and value:t7
Time Taken is:85
4.3)Executors.newFixedThreadPool
ExecutorService java.util.concurrent.Executors.newFixedThreadPool(int nThreads)
Creates a thread pool that reuses a fixed set of threads operating off a shared
unbounded queue. If any thread terminates due to a failure during execution prior to
shutdown, a new one will take its place if needed to execute subsequent tasks.

Parameters: nThreads the number of threads in the pool


Returns: the newly created thread pool

/*
* Shows threads from a pool being reused!!!
*/
public class CachePoolExecuteHash {

ConcurrentHashMap<String, String> chm = new ConcurrentHashMap<String, String>(20);


ExecutorService execservice=Executors. newFixedThreadPool (5);

public static void main (String args []) {


new CachePoolExecuteHash();
}

public CachePoolExecuteHash(){
long start= System.currentTimeMillis();
for (int i= 0; i <20; ++i){
execservice.execute(new Runner(chm,"t"+i,50
}
Iterator<String > keys= chm.keySet().iterator();

while(keys.hasNext()){
String key=keys.next();
System.out.println("MainThread read Key:" + key+
" and value:" + chm.get(key) );
}
long stop=System.currentTimeMillis();
long timeTaken = stop-start;
System.out.println("Time Taken is:"+ timeTaken);
}


MainThread read Key:pool-1-thread-4-23 and value:t19
MainThread read Key:pool-1-thread-4-0 and value:t19

MainThread read Key:pool-1-thread-4-32 and value:t19
MainThread read Key:pool-1-thread-4-42 and value:t19
MainThread read Key:pool-1-thread-4-15 and value:t19

MainThread read Key:pool-1-thread-1-2 and value:t6
MainThread read Key:pool-1-thread-4-21 and value:t19

MainThread read Key:pool-1-thread-1-8 and value:t6
MainThread read Key:pool-1-thread-4-38 and value:t19

MainThread read Key:pool-1-thread-5-22 and value:t4
MainThread read Key:pool-1-thread-5-44 and value:t4
MainThread read Key:pool-1-thread-5-14 and value:t4
Time Taken is:38

 
4.3)Executors.newCachedThreadPool
java.util.concurrent.Executors.newCachedThreadPool()
Creates a thread pool that creates new threads as needed, but will reuse previously
constructed threads when they are available. These pools will typically improve the
performance of programs that execute many short-lived asynchronous tasks. Calls to
execute will reuse previously constructed threads if available. If no existing thread is
available, a new thread will be created and added to the pool. Threads that have not been
used for sixty seconds are terminated and removed from the cache. Thus, a pool that
remains idle for long enough will not consume any resources. Note that pools with similar
properties but different details (for example, timeout parameters) may be created using
ThreadPoolExecutor constructors.

Returns: the newly created thread pool

public class CachePoolExecuteHash {


ConcurrentHashMap<String, String> chm = new ConcurrentHashMap<String, String>(20);
ExecutorService execservice=Executors.newCachedThreadPool();
public static void main (String args []) {
new CachePoolExecuteHash();
}

public CachePoolExecuteHash(){
long start= System.currentTimeMillis();
for (int i= 0; i <20; ++i){
execservice.execute(new Runner(chm,"t"+i,50));
}
Iterator<String > keys= chm.keySet().iterator();

while(keys.hasNext()){
String key=keys.next();
System.out.println("MainThread read Key:" + key+
" and value:" + chm.get(key));
}
long stop=System.currentTimeMillis();
long timeTaken = stop-start;
System.out.println("Time Taken is:"+ timeTaken);
}
}

MainThread read Key:pool-1-thread-19-27 and value:t18


MainThread read Key:pool-1-thread-8-49 and value:t7
MainThread read Key:pool-1-thread-19-49 and value:t18
……
MainThread read Key:pool-1-thread-20-12 and value:t19
MainThread read Key:pool-1-thread-20-17 and value:t19
MainThread read Key:pool-1-thread-20-47 and value:t19
MainThread read Key:pool-1-thread-20-18 and value:t19
MainThread read Key:pool-1-thread-20-25 and value:t19
MainThread read Key:pool-1-thread-20-19 and value:t19
MainThread read Key:pool-1-thread-20-10 and value:t19
MainThread read Key:pool-1-thread-20-32 and value:t19
Time Taken is:124

You might also like