Using Java Stream API in already multi-threaded environment - java-8

My application has its own thread pool(myThreadPool) and I am assigning one of its threads(Producer) to read a file via java stream API. But in runtime stream is lost somewhere and never reaches the print method. But when I run the stream in single threaded environment it works. Does it happen because java stream Api uses its own thread pool underneath or is this conceptually wrong?
public class Processor {
public void process() {
ExecutorService myThreadPool = Executors.newFixedThreadPool(3);
myThreadPool.execute(new Producer());
}
private class Producer implements Runnable{
#Override
public void run() {
try (Stream<String> lines = Files.lines(Paths.get("Path"))) {
System.out.println(lines.count());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

I don't know what you have happen. but I can give you an advice (maybe your program exited and Producer is not terminated). copy this code and see what wrong of your code.
public class Processor {
public void process() {
ExecutorService myThreadPool = Executors.newFixedThreadPool(3);
try {
myThreadPool.execute(new Producer());
Thread.currentThread().join();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private class Producer implements Runnable {
#Override
public void run() {
try (Stream<String> lines = Files.lines(Paths.get("Path"))) {
System.out.println(lines.count());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OR
public class Processor {
public void process() {
ExecutorService myThreadPool = Executors.newFixedThreadPool(3);
try {
myThreadPool.submit(() -> {
new Producer().run();
return null;
}).get();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private class Producer implements Runnable {
#Override
public void run() {
try (Stream<String> lines = Files.lines(Paths.get("Path"))) {
System.out.println(lines.count());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Related

transaction error when explicit exception handling in spring

I've found that there is a difference between being explicit and not having the same exception thrown.
1.
public class FooService {
#Transactional
public void foo() {
try {
fooRepository.save(foo); // when DataIntegrityViolationException!!
} catch(DataIntegrityViolationException e) {
log.error("foo error");
}
}
}
public class Caller {
public void caller() {
try {
fooService.foo();
} catch(Exception e) {
log.error("Caller error"); // happen
}
}
}
In the case of example 1, DataIntegrityViolationException occurs because it violates the constraint when saving. In the log, a caller error is output and Unexpect~Exception is caught.
On the other hand, if an explicit DataIntegrityViolationException is thrown, no caller error is stamped.
2.
public class FooService {
#Transactional
public void foo() {
try {
fooRepository.save(foo); // when success
if (true) {
throw new DataIntegrityViolationException("ex");
}
} catch(DataIntegrityViolationException e) {
log.error("foo error");
}
}
}
public class Caller {
public void caller() {
try {
fooService.foo();
} catch(Exception e) {
log.error("Caller error"); // not logging
}
}
}
There is no difference when explicitly calling an exception in the Spring documentation. I wonder why this happened.

ControllerAdvice is not triggered in my springboot application?

Actually I am working in a Kafka streams application using Spring Boot.
So here I am trying to handle exceptions globally using #ControllerAdvice but it is not working for me.
Is it possible to use #ControllerAdvice in my application.
Is this controller advice is only works when the error is coming from controller.
Note: I am not having any controller / rest controller endpoints in my application.
Can we achieve the same in some other ways?
Please share your valuable thoughts!
Main Stream:
#Autowired
private XyzTransformer xyztransformer;
#Bean
public KStream<String, ABC> processMember(#Qualifier("defaultKafkaStreamsBuilder") StreamsBuilder streamsBuilder) {
try {
LOGGER.info("streaming started...");
KStream<String, Xyz> xyStream = streamsBuilder.stream(appProperty.kafkaStreamsTopicInput)
.transformValues(() -> xyztransformer)
xyStream.to(appProperty.kafkaStreamsTopicOutput);
return memberStream;
} catch (Exception ex) {
LOGGER.error("Exception occurred in Streams " + Arrays.toString(ex.getStackTrace()));
throw ex;
}
}
TransformerClass:
#Component
public class XyzTransformer implements ValueTransformer<Xyz, Abc> {
#Override
public void close() {
}
#Override
public void init(ProcessorContext processorContext) {
}
#SneakyThrows
#Override
public Abc transform(Xyz data) {
String[] dataSourceTables = new String[]{"abc"};
try {
return Abc.builder()
.name(data.getName())
.build();
} catch (Exception ex) {
System.out.println("catched and throwing");
throw new CustomTesException("test 1");
}
}
}
ControllerAdvice:
#ControllerAdvice
public class Advice extends ResponseEntityExceptionHandler {
#ExceptionHandler(NullPointerException.class)
public final void handleAllExceptions(NullPointerException ex) {
System.out.println("it is in the handler");
System.out.println(ex.getMessage());
}
#ExceptionHandler(Exception.class)
public final void handleAllException(Exception ex) {
System.out.println("it is in the exception handler");
System.out.println(ex.getMessage());
}
#ExceptionHandler(CustomTesException.class)
public final void handleAllExceptio(CustomTesException ex) {
System.out.println("it is in the exception handler");
System.out.println(ex.getMessage());
}
}

How to schedule service in Apache Felix?

I have deployed some Declarative Services OSGI in my bundle. After my bundle is started, these Services are activated and do some code in run() of Thread. However, I would like to schedule the time to start the run().
#Component(name = "ABC"
,immediate = true
,enabled = true)
public class test {
private volatile boolean isStarted;
#Activate
public void activate() {
System.out.println("activate");
final Thread t = new Thread() {
public void run() {
runIt();
}
};
t.setDaemon(true);
isStarted = true;
t.start();
}
#Deactivate
public void deactivate() {
System.out.println("DEactivate");
isStarted = false;
}
private void runIt() {
while (isStarted) {
System.out.println("OK");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Java CompletableFuture - main class not terminated

I am trying to implment CompletableFuture which invokes a dummy callback method when completed.
However, after adding CompletableFuture.get() method my main class doesn't terminate.
I tried replacing CompletableFuture.get() with Thread.sleep(5000) but it doesn't seem to be right approach.
Please suggest what is causing CompletableFuture.get() to keep blocking even if the thread is complete.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture=new CompletableFuture<String>();
compFuture.supplyAsync(()->{
//Compute total
long count=IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return ""+count;
}).thenApply(retVal->{
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
);
System.out.println("Main Thread 1");
try {
compFuture.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
class CallBackAsynchClass
{
String returnVal="";
public CallBackAsynchClass(String ret) throws InterruptedException, ExecutionException {
System.out.println("Callback invoked:"+ret);
returnVal=ret;
}
#Override
public String toString() {
return "CallBackAsynchClass [returnVal=" + returnVal + "]";
}
}
I am expecting "Lock cleared" to be outputted but .get() seems to be holding up the lock.
.thenApply function returns a new instance of CompletableFuture, and it's this instance that you need to use, try using this way instead :
public class CallableAsyncWithCallBack {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> compFuture = CompletableFuture.supplyAsync(() -> {
//Compute total
long count = IntStream.range(Integer.MIN_VALUE, Integer.MAX_VALUE).count();
return "" + count;
});
CompletableFuture<String> future = compFuture.thenApply(retVal -> {
try {
return new CallBackAsynchClass(retVal).toString();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""; });
System.out.println("Main Thread 1");
try {
future.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Lock cleared");
}
}
Hope this helps

Spring AOP Not working properly

I'm trying to handle exceptions with AOP approach in my Spring/Swing Application and I couldn't make it work.
Main Class:
public class MainFrame extends JFrame {
private JPanel mainPanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainFrame() {
initializeMainPanel();
}
private void initializeMainPanel() {
exitLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
throw new Exception("test");
}
});
}
}
Aspect Class:
#Aspect
public class AspectTest{
#AfterThrowing(pointcut = "execution(* com.test.MainFrame.*(..))", throwing = "ex")
public void logError(Exception ex) throws Throwable {
// ex.printStackTrace();
}
}
So, I throw an exception within my Mouse Listener and expect to catch it in my AspectTest class' AfterThrowing method but it does not work.
Can someone please help me to understand what I'm missing here?
#AfterThrowing cannot catch exceptions, only notice them and log them or do something similar. If you want to handle exceptions in an aspect you need to use an #Around advice.

Resources