I have written the following code, as I was trying to understand the situation where I would use ThreadLocals:-
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDF {
private DateFormat df = new SimpleDateFormat("MM/dd/yy");
public String formatCurrentDate() {
System.out.println(">>>>>>>"+Thread.currentThread().getName());
Date d = new Date();
return df.format(d);
}
public String formatFirstOfJanyary1970() {
System.out.println(">>>>>>>" + Thread.currentThread().getName());
Date d = new Date(0);
return df.format(d);
}
public static void main(String[] args) {
TestDF df = new TestDF();
Thread t1 = new Thread(new WorkerThread(df));
Thread t2 = new Thread(new WorkerThread1(df));
t1.start();
t2.start();
}
public static class WorkerThread implements Runnable {
TestDF df;
public WorkerThread(TestDF df) {
this.df = df;
}
#Override
public void run() {
Thread.currentThread().setName("Worker-Thread 1");
System.out.println("Inside Thread1*");
System.out.println("Thread 1 "+df.formatCurrentDate());
System.out.println("Inside Thread1**");
try {
Thread.sleep(5000l);
System.out.println("Inside Thread1***");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class WorkerThread1 implements Runnable {
TestDF df;
public WorkerThread1(TestDF df) {
this.df = df;
}
#Override
public void run() {
Thread.currentThread().setName("Worker-Thread 2");
System.out.println("Inside Thread2*");
System.out.println("Thread 2 "+df.formatFirstOfJanyary1970());
System.out.println("Inside Thread2**");
try {
Thread.sleep(5000l);
System.out.println("Inside Thread2***");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The out which I am receiving is as follows:-
Inside Thread1*
Inside Thread2*
>>>>>>>Worker-Thread 2
>>>>>>>Worker-Thread 1
Thread 1 06/09/15 <--
Thread 2 06/09/15 <--
Inside Thread1**
Inside Thread2**
Inside Thread1***
Inside Thread2***
I am aware that SimpleDateFormat is not thread-safe; but still couldn't make out how is happening.
Related
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
I have the following application.yml:
service:
kafka:
groupId: 345
consumer:
topics:
-
name: response
producer:
topics:
-
name: request1
num-partitions: 5
replication-factor: 1
-
name: request2
num-partitions: 3
replication-factor: 1
How can I access the list of topic names using spel for passing to KafkaListener annotation?
#KafkaListener(topics = "#{'${service.kafka.consumer.topics.name}'}", containerFactory = "kafkaListenerContainerFactory")
public void receive(String payload, #Header(KafkaHeaders.RECEIVED_TOPIC)String topic) {
Use configuration properties and collection projection...
#ConfigurationProperties("service.kafka.producer")
#Component
public class ConfigProps {
List<Topic> topics = new ArrayList<>();
public List<Topic> getTopics() {
return this.topics;
}
public void setTopics(List<Topic> topics) {
this.topics = topics;
}
#Override
public String toString() {
return "ConfigProps [topics=" + this.topics + "]";
}
public static class Topic {
private String name;
private int numPartitions;
private short replicationFactor;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getNumPartitions() {
return this.numPartitions;
}
public void setNumPartitions(int numPartitions) {
this.numPartitions = numPartitions;
}
public short getReplicationFactor() {
return this.replicationFactor;
}
public void setReplicationFactor(short replicationFactor) {
this.replicationFactor = replicationFactor;
}
#Override
public String toString() {
return "Topic [name=" + this.name + ", numPartitions=" + this.numPartitions + ", replicationFactor="
+ this.replicationFactor + "]";
}
}
}
and
#SpringBootApplication
public class So52741016Application {
public static void main(String[] args) {
SpringApplication.run(So52741016Application.class, args);
}
#KafkaListener(groupId = "${service.kafka.groupId}", topics = "#{configProps.topics.![name]}")
public void listener(String in) {
}
#Bean
public SmartLifecycle createTopics(KafkaAdmin admin, ConfigProps props) {
return new SmartLifecycle() {
#Override
public int getPhase() {
return Integer.MIN_VALUE;
}
#Override
public void stop() {
}
#Override
public void start() {
try (AdminClient client = AdminClient.create(admin.getConfig())) {
CreateTopicsResult createTopics = client.createTopics(props.topics.stream()
.map(t -> new NewTopic(t.getName(), t.getNumPartitions(), t.getReplicationFactor()))
.collect(Collectors.toList()));
createTopics.all().get();
}
catch (Exception e) {
// e.printStackTrace();
}
}
#Override
public boolean isRunning() {
return false;
}
#Override
public void stop(Runnable callback) {
}
#Override
public boolean isAutoStartup() {
return true;
}
};
}
}
and
2018-10-10 11:20:25.813 INFO 14979 --- [ntainer#0-0-C-1] o.s.k.l.KafkaMessageListenerContainer : partitions assigned: [request1-4, request2-0, request1-0, request2-1, request1-1, request2-2, request1-2, request1-3]
Of course, this is only the producer topics, but you can handle them all this way.
I am learning how to use rxjava. As shown in the code below, I have List<List<Person>> what i am planning to do is to iterate throught all the lists of Person
and to display how many object of type Person in each list.
I coded the following:
.map(p->p.get(0).getName().map(r->r.toUpperCase()).orElse("NULL_VALUE"))
but as you see i always reference the item number 0. how can i reference all the items in the list as if I am using for-loop as folows:
for (int i = 0; i< length; i++)
p.get(i)
i hope my question is clear.
thanks in advance
code:
public static void main(String[] args) {
Observable<List<Person>> observables = Observable.create(e-> {
for(List<Person> p : Main.getPersons()) {
e.onNext(p);
}
e.onComplete();
});
observables
.map(p->p.get(0).getName().map(r->r.toUpperCase()).orElse("NULL_VALUE"))
.doOnNext(r->System.out.println("r: " + r))
.observeOn(Schedulers.io())
.subscribe(new Observer() {
#Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("onCompleted");
}
#Override
public void onError(Throwable arg0) {
// TODO Auto-generated method stub
}
#Override
public void onNext(Object arg0) {
// TODO Auto-generated method stub
System.out.println("onNextFromObserver: " + arg0);
}
#Override
public void onSubscribe(Disposable arg0) {
// TODO Auto-generated method stub
}
});
}
private static <T> Observable<T> toObservable(T s) {
return Observable.just(s);
}
private static List<List<Person>> getPersons() {
return Arrays.asList(
Arrays.asList(new Person("Sanna1", 59, "EGY"), new Person(null, 59, "EGY"), new Person("Sanna3", 59, null)),
Arrays.asList(new Person("Mohamed1", 59, "EGY"), new Person(null, 59, "EGY")),
Arrays.asList(new Person("Ahmed1", 44, "QTR"), new Person("Ahmed2", 44, "QTR"), new Person(null, null, "QTR")),
Arrays.asList(new Person("Fatma", 29, "KSA")),
Arrays.asList(new Person("Lobna", 24, "EGY")));
}
}
Person
public class Person {
private String name = null;
private String address = null;
private int age;
private Optional<String> optName= null;
private Optional<Integer> optAge= null;
private Optional<String> optAddress = null;
public Person(String name, Integer age, String address) {
this.optName = Optional.ofNullable(name);
this.optAge = Optional.ofNullable(age);
this.optAddress = Optional.ofNullable(address);
}
public Optional<String> getName() {
return optName;
}
public void setName(String name) {
this.optName = Optional.ofNullable(name);
}
public Optional<String> getAddress() {
return this.optAddress;
}
public void setAddress(String address) {
this.optAddress = Optional.ofNullable(address);
}
public Optional<Integer> getAge() {
return this.optAge;
}
public void setAge(int age) {
this.optAge = Optional.ofNullable(age);
}
}
update
public static void main(String[] args) {
Observable<List<Person>> observables =
Observable.fromIterable(Main.getPersons());
observables
//.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.concatMap(list->Observable.fromIterable(list)
.map(p->p.getName()
.map(r->r.toUpperCase()).orElse("NULL_VALUE")))
.observeOn(Schedulers.io())
.blockingSubscribe(new Observer<String>() {
#Override
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("onComplete: ");
}
#Override
public void onError(Throwable arg0) {
// TODO Auto-generated method stub
System.out.println("onError: ");
}
#Override
public void onNext(Object arg0) {
// TODO Auto-generated method stub
System.out.println("onNext: ");
}
#Override
public void onSubscribe(Disposable arg0) {
// TODO Auto-generated method stub
System.out.println("onSubscribe: ");
}
});
}
Use fromIterables and concatMap:
public static void main(String[] args) {
Observable<List<Person>> observables =
Observable.fromIterable(Main.getPersons());
observables
.concatMap(personList ->
Observable.fromIterable(personList)
.map(aPerson ->
aPerson.getName()
.map(name -> name.toUpperCase()).orElse("NULL_VALUE")
)
)
.doOnNext(aName -> System.out.println("aName: " + aName))
.observeOn(Schedulers.io())
.blockingSubscribe(new Observer<String>() {
#Override
public void onComplete() {
System.out.println("onCompleted");
}
#Override
public void onError(Throwable ex) {
ex.printStackTrace();
}
#Override
public void onNext(String item) {
System.out.println("onNextFromObserver: " + item);
}
#Override
public void onSubscribe(Disposable disposable) {
}
});
}
How can I create a Spring Aspect (annotation driven e.g. #ExceptionTranslation) surrounding an entire method and put this method in a try...catch method?
#ExceptionTranslation
public void method() {
// do some stuff here...
}
so logically it does:
public void method() {
try {
// do some stuff here ...
} catch( Exception ex ) {
}
}
Below you can find a sample implementation of AfterThrows advice solving your problem.
CustomException.java
package com.yourpackage;
public class CustomException extends Exception {
public CustomException(final Throwable cause) {
super(cause);
}
}
ErrorBean.java
package com.yourpackage;
public class ErrorBean {
#ExceptionTranslation
public void translatedException() throws Exception {
throw new Exception("Foo");
}
public void notTranslatedException() throws Exception {
throw new Exception("Bar");
}
}
ExceptionTranslation.java
package com.yourpackage;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface ExceptionTranslation {
}
SimpleThrowsAdvice.java
package com.yourpackage;
import org.springframework.aop.Advisor;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
public class SimpleThrowsAdvice implements ThrowsAdvice {
public static void main(String[] args) throws Exception {
ErrorBean errorBean = new ErrorBean();
AnnotationMatchingPointcut pc = AnnotationMatchingPointcut.forMethodAnnotation(ExceptionTranslation.class);
SimpleThrowsAdvice advice = new SimpleThrowsAdvice();
Advisor advisor = new DefaultPointcutAdvisor(pc, advice);
ProxyFactory pf = new ProxyFactory();
pf.setTarget(errorBean);
pf.addAdvisor(advisor);
ErrorBean proxy = (ErrorBean) pf.getProxy();
try {
proxy.translatedException();
} catch (CustomException ex) {
System.out.println("CustomException caught");
} catch (Exception ex) {
System.out.println("Exception caught");
}
try {
proxy.notTranslatedException();
} catch (CustomException ex) {
System.out.println("CustomException caught");
} catch (Exception ex) {
System.out.println("Exception caught");
}
}
public void afterThrowing(Exception ex) throws Throwable {
System.out.println("***");
System.out.println("Generic Exception Capture");
System.out.println("Caught: " + ex.getClass().getName());
System.out.println("***\n");
throw new CustomException(ex);
}
}
I have a Sample WebSocket Program whown below which works fine
When ever the user closes the browser or if there is any excetion Or any disconnect , the onClose Method is
being called
My question is that , Is it possible to know from the program what is the reason for onClose being called ??
Please share your views , Thanks for reading .
public class Html5Servlet extends WebSocketServlet {
private AtomicInteger index = new AtomicInteger();
private static final List<String> tickers = new ArrayList<String>();
static{
tickers.add("ajeesh");
tickers.add("peeyu");
tickers.add("kidillan");
tickers.add("entammo");
}
/**
*
*/
private static final long serialVersionUID = 1L;
public WebSocket doWebSocketConnect(HttpServletRequest req, String resp) {
//System.out.println("doWebSocketConnect");
return new StockTickerSocket();
}
protected String getMyJsonTicker() throws Exception{
return "";
}
public class StockTickerSocket implements WebSocket.OnTextMessage{
private Connection connection;
private Timer timer;
#Override
public void onClose(int arg0, String arg1) {
System.out.println("onClose called!"+arg0);
}
#Override
public void onOpen(Connection connection) {
//System.out.println("onOpen");
this.connection=connection;
this.timer=new Timer();
}
#Override
public void onMessage(String data) {
//System.out.println("onMessage");
if(data.indexOf("disconnect")>=0){
connection.close();
timer.cancel();
}else{
sendMessage();
}
}
public void disconnect() {
System.out.println("disconnect called");
}
public void onDisconnect()
{
System.out.println("onDisconnect called");
}
private void sendMessage() {
if(connection==null||!connection.isOpen()){
//System.out.println("Connection is closed!!");
return;
}
timer.schedule(new TimerTask() {
#Override
public void run() {
try{
//System.out.println("Running task");
connection.sendMessage(getMyJsonTicker());
}
catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new Date(),5000);
}
}
}
The signature for onClose is the following ...
#Override
public void onClose(int closeCode, String closeReason) {
System.out.println("onClose called - statusCode = " + closeCode);
System.out.println(" reason = " + closeReason);
}
Where int closeCode is any of the registered Close Status Codes.
And String closeReason is an optional (per protocol spec) close reason message.