concurrent execution of thread
Thread: unit of execution within the process
Thread Pool: group of worker threads that are waiting for the job and reuse many times.
Java thread dump: snapshot of all threads state running within JVM at a particular moment.
public class MyThread extends Thread {
public void run() { System.out.println("Thread started running.."); }
public static void main( String args[] ) {
MyThread mt = new MyThread();
mt.start();
}
}
class MyThread implements Runnable {
public void run() { System.out.println("Thread started running.."); }
public static void main(String args[]) {
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Thread scheduler prioritize based on (Range 1-10) (default-5)
threadObj.setPriority(8);
threadObj.setPriority(Thread.MIN_PRIORITY) //1
threadObj.setPriority(Thread.MAX_PRIORITY) //10
threadObj.setPriority(Thread.NORM_PRIORITY) //5
Daemon threads - low priority threads which always run in background. Ex:Garbage collector
t1.setDaemon(true);t1.isDaemon(true);
thread3.join(); thread4.join(200); //wait for 200ms
Thread.sleep(1000);
//goes to runnable for given time Map<String, String> results = new ConcurrentHashMap<>();
Thread thread1 = new Thread(() -> results.put("Thread 1", "Result from Thread 1"));
Thread thread2 = new Thread(() -> results.put("Thread 2", "Result from Thread 2"));
thread1.start(); thread2.start();
// Wait for each thread to complete using join()
thread1.join();thread2.join();
System.out.println(results.get("Thread 1"));
System.out.println(results.get("Thread 2"));
allow only one thread to access the shared resource.
Race condition: When multiple threads try to access same resources
situation where a set of processes are blocked
because each process is holding a resource and waiting for another resource acquired by some other process.
How to resolve: try to interrupt thread1 and later call it
if (thread1.getState() == Thread.State.BLOCKED && thread2.getState() == Thread.State.BLOCKED) {thread1.interrupt();}
Interrupting Thread:
introduced in java5(2004). to make multithreading easier, safer, and more efficient.
interface from java.util.concurrent, manages and executes asynchronous tasks concurrently
Syntax:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> { // Task to be executed asynchronously});
executor.submit(new MyRunnableImpl());
executor.shutdown();
Methods of ExecuterService:
class that implements ExecutorService, offers more control and customization options.
Syntax:
ThreadPoolExecutor mypool = (ThreadPoolExecutor) executorServiceObj;
mypool.submit(() -> { // Task to be executed asynchronously});
mypool.submit(new MyRunnableImpl());
System.out.println("size of mypool: " + mypool.getPoolSize());
System.out.println("Total number threads scheduled): "+ mypool.getTaskCount());
mypool.shutdown();
Callable: interface that represents task, have call method that returns result.
Future: interface that represent result of callable->call method
Callable<Integer> callableTask = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(2000);
return 42;
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callableTask);
Future<Integer> future2 = executorService.submit(callableTask);
Integer result = future.get(); //will block/wait until Future is complete.
Integer result2 = future2.get(); //will block/wait until Future2 is complete.
System.out.println("Result: " + result); // Output: Result: 42
executorService.shutdown();
List<Integer> list = new ArrayList<>();
List<Integer> synchronizedList = Collections.synchronizedList(list);
Collections.addAll(synchronizedList, 1, 2, 3);
// Accessing elements in a synchronized block to avoid ConcurrentModificationException
synchronized (synchronizedList) {
for (Integer i : synchronizedList) {
System.out.println(i);
}
}
synchronized works in variable level, and it has some methods
provides atomicity.