closing statically created executorservice blocks assigned variables itself? - java

I just wonder explanation of how this code is working
assume we have Work class in below
public class Work {
private static ThreadPoolExecutor executorService;
private Work(){};
public static void instansiate(int numberOfThread){
executorService= (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThread);
}
public static void shutDown(){
executorService.shutdown();
}
public static ExecutorService getExecutorService() {
return executorService;
}
public static int getThreadCount(){
return executorService.getCorePoolSize();
}
}
and im calling this class somewhere in method like below
public static void xx() throws ExecutionException, InterruptedException {
Work.instansiate(2);
System.out.println("Thread count= " + Work.getThreadCount());
ExecutorService executorService = Work.getExecutorService();
Future<String> future1 = executorService.submit(new Callable<String>() {
#Override
public String call() throws Exception {
return "future1";
}
});
String resFuture1 = future1.get();
System.out.println(resFuture1);
Work.shutDown();
Future<String> future2 = executorService.submit(new Callable<String>() {
#Override
public String call() throws Exception {
return "future2";
}
});
String resFuture2 = future2.get();
System.out.println(resFuture2);
}
This code is throwing exception after Work.shutDown() line and says rejected from java.util.concurrent.ThreadPoolExecutor#234bef66[Terminated, pool size = 0, active threads = 0 ...
I had assigned Work.getExecutorService to another executorService how closing Work executorservice can block assigned one.

Actually executorService holding same reference with Work.executorService(), Thus it was affected of closing Work's executorservice.

Related

Not able to break classic lazy initialization Singleton

I am trying to create various singleton patterns and check for breaks using millions of threads. I was hoping this would lead me to implement Bill Pugh ultimately. But I am not even able to break the classical one.
Singleton: Previously tried a million threads, all were having same hashcode. So I made it sleep for 10 sec so that both threads are sure to enter null check condition but all in frustration.
package demo2;
public class Singleton {
private static Singleton soleInstance = null;
private Singleton() throws InterruptedException {
}
public static Singleton getInstance() throws InterruptedException {
if (soleInstance == null) {
Thread.sleep(10000);
soleInstance = new Singleton();
}
return soleInstance;
}
}
Test Class:
package demo2;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
class Test {
public int makeSingleton() throws InterruptedException {
Singleton s = Singleton.getInstance();
return s.hashCode();
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Test t = new Test();
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 2; i++) {
Future<Integer> future = executor.submit(new Callable<Integer>() {
public Integer call() throws InterruptedException {
return t.makeSingleton();
}
});
list.add(future.get());
}
executor.shutdown();
List<Integer> list2 = list.stream().distinct().collect(Collectors.toList());
System.out.println(list2);
}
}
How the hell do I break it?
Below mentioned code will work.
Change your code. May be you are calling get inside method only and it's waiting to get results & loop count won't increment.
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Future<Integer>> list = new ArrayList<Future<Integer>>();
for (int i = 0; i < 5; i++) {
Future<Integer> future = executor.submit(new Callable<Integer>() {
public Integer call() throws InterruptedException {
return Singleton.getInstance().hashCode();
}
});
list.add(future);
}
executor.shutdown();
Set<Integer> output = new HashSet<Integer>();
for(Future<Integer> future : list){
output.add(future.get());
}
System.out.println(output);
Please check this:
/**
* <p>
* If you would like to immediately block waiting
* for a task, you can use constructions of the form
* {#code result = exec.submit(aCallable).get();}
*/
<T> Future<T> submit(Callable<T> task);
If you use
Future<Integer> future = executor.submit(new Callable<Integer>()
it will block you thread till the result return.
If you want to break the classical singleton pattern, try this code
public class BreakSingleton {
public MySingleton makeSingleton() throws InterruptedException {
MySingleton s = MySingleton.getInstance();
return s;
}
public static void main(String[] args) throws Exception {
BreakSingleton t = new BreakSingleton();
ExecutorService executor = Executors.newFixedThreadPool(2);
final List<MySingleton> list = new ArrayList<>();
System.out.println(Thread.currentThread().getName());
for (int i = 0; i < 2; i++) {
executor.submit(new Callable<MySingleton>() {
public MySingleton call() throws InterruptedException {
MySingleton mySingleton = t.makeSingleton();
list.add(mySingleton);
return mySingleton;
}
});
}
executor.shutdown();
Thread.sleep(5000);
System.out.println(list);
}
}
class MySingleton {
private static MySingleton instance = null;
private MySingleton() {
}
public static MySingleton getInstance() throws InterruptedException {
System.out.println(Thread.currentThread().getName());
if (instance == null) {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName());
instance = new MySingleton();
}
return instance;
}
}

Calling async method from another method without waiting/blocking

I have one webservice which is called by client.
public class MyWebServiceClass {
public int myMethod() {
myAsyncMethodInAnotherClass();
return 2;
}
}
I have another class which is acync, this class have method
public void myAsyncMethodInAnotherClass() throws InterruptedException, ExecutionException {
final Receiver receiver = new Receiver();
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future future = executorService.submit(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
receiver.doSomeThingElse();
}
});
executorService.shutdown();
}
I want myMethod() inside MyWebServiceClass should return 2 to the client, without waiting for process inside myAsyncMethodInAnotherClass(). Though I have created executorService but it is still waiting for method to complete before returning 2.

How to get the output stream from a thread

I currently have several runnable classes, each printing a string upon completion using System.out.println().
In the main() I execute them using a ExecutorService ,executor.execute() for each of them.
I am wondering after executing those threads, how to get the output stream from them for future use ?
Pretty much like using .getInputStream for processes but there's no such method in the Thread class. Thanks!
There's a class which implements runnable interface like this:
public class A implements Runnable {
public void run() {
System.out.println(5); //this thread always print out number 5
}
}
and in the main function I need to get the printed number and store it
public static void main(String[] args) {
ExecutorService ThreadPool = Executors.newFixedThreadPool(1);
ThreadPool.execute(new A()); //This statement will cause the thread object A
//to print out number 5 on the screen
ThreadPool.shutdown();
......
}
Now I need to get the printed number 5 and store it into, say an integer variable.
I think below code will satisfy your requirement.
class MyCallable implements Callable<InputStream>
{
#Override
public InputStream call() throws Exception {
//InputStream inputStreamObject = create object for InputStream
return inputStreamObject;
}
}
class Main
{
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<InputStream>> list = new ArrayList<Future<InputStream>>();
for (int i = 0; i < 25; i++) {
Callable<InputStream> worker = new MyCallable();
Future<InputStream> submit = executor.submit(worker);
list.add(submit);
}
InputStream inputStreamObject = null;
for (Future<InputStream> future : list) {
try {
inputStreamObject = future.get();
//use inputStreamObject as your needs
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}
Runnable and Callable in thread:
runnable interface has a method public abstract void run(); void - which means after completing run method, it will not return anything. Callable<V> interface has a method V call() throws Exception; which means after completing call method, it will return Object V that is parametrized as
public class Run_Vs_Call {
public static void main(String...args){
CallableTask call = new CallableTask();
RunnableTask run = new RunnableTask();
try{
FutureTask<String> callTask = new FutureTask<String>(call);
Thread runTask = new Thread(run);
callTask.run();
runTask.start();
System.out.println(callTask.get());
}catch(Exception e){
e.printStackTrace();
}
}
public static class CallableTask implements Callable<String>{
public String call( ){
String stringObject = "Inside call method..!! I am returning this string";
System.out.println(stringObject);
return stringObject;
}
}
public static class RunnableTask implements Runnable{
public void run(){
String stringObject = "Inside Run Method, I can not return any thing";
System.out.println(stringObject);
}
}
}
you can use new static class:
public class Global{
//example
public static ..
public static ..
}

Control Over Termination Threads in Java Executor-framework

Note: I'm new to english, so please forgive me for any wrong in it.
I use thread-local for save a resource per-thread; and use it(thread-local) in a some tasks. I run my task by a java executor-service. I would close my resources when a thread going to terminate; then i need run a task in all created threads by executor-service, after me call "executor.shoutdown" method. how i can force executor to run a task per-thread, when it would terminate those?
import java.util.concurrent.*;
public class Main2 {
public static void main(String[] args) {
ExecutorService executor = new ForkJoinPool(3);
SimpleValue val = new SimpleValue();
for(int i=0; i<1000; i++){
executor.execute(new Task(val));
}
executor.shutdown();
while( true ) {
try {
if( executor.awaitTermination(1, TimeUnit.SECONDS) ) System.exit(0);
} catch(InterruptedException intrExc) {
// continue...
}
}
}
protected static interface ResourceProvider<T>
extends AutoCloseable {
public T get();
public ResourceProvider<T> reset() throws Exception;
public ResourceProvider<T> reset(boolean force) throws Exception;
public void close();
}
protected static abstract class ThreadLocalResourceProvider<T>
extends ThreadLocal<T>
implements ResourceProvider<T> {}
protected static class SimpleValue
extends ThreadLocalResourceProvider<String> {
public String initialValue() {
return "Hello " + Thread.currentThread().getName();
}
public SimpleValue reset() throws Exception {
return reset(false);
}
public SimpleValue reset(boolean force) throws Exception{
set(this.initialValue());
return this;
}
public void close() {
remove();
}
}
protected static class Task
implements Runnable {
protected SimpleValue val;
public Task(SimpleValue val) {
this.val = val;
}
#Override
public void run() {
try {
System.out.print(val.reset().get());
} catch( Exception exc ) {
System.out.print( exc.getMessage() );
}
}
}
}
Most executors can be constructed with a ThreadFactory. That's also true for ForkJoinPool. However, for simplification, I use a different ExecutorService.
ExecutorService executor = Executors.newFixedThreadPool(
10, new FinalizerThreadFactory(Executors.defaultThreadFactory()));
The class FinalizerThreadFactory delegates the creation of threads to the passed thread factory. However, it creates threads that will execution some additional code before they exit. That's quite simple:
class FinalizerThreadFactory implements ThreadFactory {
private final ThreadFactory delegate;
public FinalizerThreadFactory(ThreadFactory delegate) {
this.delegate = delegate;
}
public Thread newThread(final Runnable r) {
return delegate.newThread(new Runnable() {
public void run() {
try {
r.run();
} finally {
// finalizer code goes here.
}
}
});
}
}

ForkJoinPool resets thread interrupted state

I just noticed the following phenomena when cancelling a Future returned by ForkJoinPool. Given the following example code:
ForkJoinPool pool = new ForkJoinPool();
Future<?> fut = pool.submit(new Callable<Void>() {
#Override
public Void call() throws Exception {
while (true) {
if (Thread.currentThread().isInterrupted()) { // <-- never true
System.out.println("interrupted");
throw new InterruptedException();
}
}
}
});
Thread.sleep(1000);
System.out.println("cancel");
fut.cancel(true);
The program never prints interrupted. The docs of ForkJoinTask#cancel(boolean) say:
mayInterruptIfRunning - this value has no effect in the default implementation because interrupts are not used to control cancellation.
If ForkJoinTasks ignore interrupts, how else are you supposed to check for cancellation inside Callables submitted to a ForkJoinPool?
This happens because Future<?> is a ForkJoinTask.AdaptedCallable which extends ForkJoinTask, whose cancel method is:
public boolean cancel(boolean mayInterruptIfRunning) {
return setCompletion(CANCELLED) == CANCELLED;
}
private int setCompletion(int completion) {
for (int s;;) {
if ((s = status) < 0)
return s;
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
if (s != 0)
synchronized (this) { notifyAll(); }
return completion;
}
}
}
It does not do any interruptions, it just sets status. I suppose this happens becouse ForkJoinPools's Futures might have a very complicated tree structure, and it is unclear in which order to cancel them.
Sharing some more light on top of #Mkhail answer:
Using ForkJoinPool execute() instead of submit() will force a failed Runnable to throw a worker exception, and this exception will be caught by the Thread UncaughtExceptionHandler.
Taking from Java 8 code:
submit is using AdaptedRunnableAction().
execute is using RunnableExecuteAction() (see the rethrow(ex)).
/**
* Adaptor for Runnables without results
*/
static final class AdaptedRunnableAction extends ForkJoinTask<Void>
implements RunnableFuture<Void> {
final Runnable runnable;
AdaptedRunnableAction(Runnable runnable) {
if (runnable == null) throw new NullPointerException();
this.runnable = runnable;
}
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) { }
public final boolean exec() { runnable.run(); return true; }
public final void run() { invoke(); }
private static final long serialVersionUID = 5232453952276885070L;
}
/**
* Adaptor for Runnables in which failure forces worker exception
*/
static final class RunnableExecuteAction extends ForkJoinTask<Void> {
final Runnable runnable;
RunnableExecuteAction(Runnable runnable) {
if (runnable == null) throw new NullPointerException();
this.runnable = runnable;
}
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) { }
public final boolean exec() { runnable.run(); return true; }
void internalPropagateException(Throwable ex) {
rethrow(ex); // rethrow outside exec() catches.
}
private static final long serialVersionUID = 5232453952276885070L;
}

Categories

Resources