How to schedule service in Apache Felix? - osgi

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();
}
}
}
}

Related

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

Using Java Stream API in already multi-threaded environment

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();
}
}
}
}

What is the impact of using #non thread-safe class?

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.

Websocket : Is it possible to know from the program what is the reason for onClose being called

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.

Jetty shuts down program

I am trying to create a GUI interface to start and stop a Jetty server with different return strings. Currently I have a start and stop button programmed and it returns "Hello World" into localhost:8080. My code is posted below, yes I have imports, removed to simplify it.
public class JettyGUI extends AbstractHandler{
private static Server server = new Server(8080);
private static boolean running = false;
private static void gui() {
JFrame frame = new JFrame("Jetty");
JButton start_button = new JButton("Start");
JButton stop_button = new JButton("Stop");
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.add(start_button);
panel.add(stop_button);
frame.add(panel);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
start_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Start pressed.");
startServer();
}
});
stop_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Stop pressed.");
JettyGUI.stopServer();
}
});
}
private static void stopServer() {
if(running == false){
System.err.println("Server is already running!");
}
else{
try {
server.stop();
}
catch (Exception ex) {
System.out.println(ex);
}
}
System.out.println("Server stopped!");
}
private static void startServer() {
if(running == true){
System.err.println("Server is already running!");
}
else{
try{
server.setHandler(new JettyGUI());
server.start();
server.join();
}
catch(Exception ex){
System.out.println(ex);
}
System.out.println("Server started!");
}
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("Hello World!"); //print this text
}
public static void main(String[] args) {
gui();
}
}
When I press the "start" button, Jetty API seems to take over my application and I can no longer press the "stop" button. Could anyone tell me a way to navigate around this or program this differently?
Thanks! :)
-Henry Harris
The server.join(); will make the current thread wait until the server is stopped.
Comment it out, as a GUI program you don't need it.

Resources