OSGI bundle and threads - java

I am new in OSGI and i have current aim. I have 10 threads, it's writing their names in a file. After recording thread sleep random 0..1 sec. This all must be a bundle. I create it, but i'm not sure Is this correct. Can any comments?
package helloworld;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import writer.StartThreads;
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Start Thred!!");
new StartThreads().Execute();
}
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye World!!");
}
}
1
package writer;
import writer.WriterLogs;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StartThreads {
public static void Execute() {
BufferedWriter writer = null;
File textFile = new File("threadLog.txt");
// if file doesnt exists, then create it
if (!textFile.exists()) {
try {
textFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer = new BufferedWriter(new FileWriter(textFile, true));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
WriterLogs wrt = new WriterLogs(writer);
Thread worker = new Thread(wrt);
worker.setName("Nisha-" + i);
worker.start();
try {
worker.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2
package writer;
import java.io.BufferedWriter;
import java.io.IOException;
public class WriterLogs implements Runnable {
private BufferedWriter writer;
public WriterLogs(BufferedWriter wr) {
this.writer = wr;
}
#Override
public void run() {
try
{
try {
synchronized(this.writer) {
this.writer.write(Thread.currentThread().getName() + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set random 0...1 s.
Thread.sleep((long)(Math.random() * 1000));
System.out.println(Thread.currentThread().getName());
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
* thread is interrupted.
*/
System.out.println( Thread.currentThread().getName() +interruptedException);
}
}
}

This is not correct. Like Boris the Spider states, when your bundle stops, you should free any resources and stop any processing the bundle was doing. So from the stop method you should somehow signal your threads to stop as soon as they can.
In practice you might get away with letting the code run, but this is definitely not how you should write your code in OSGi (which is what you're asking).

Related

Object located in the main thread is not initialized by another thread

I put together a class of an client app that should connect to a socket and it should automatically retrieve a DefaultTreeModel from the server or a simple String object as a test. The issue is that inside the main RemoteNetworking class the DefaultTreeModel or the String are successfully received but if I try to get them using getClientTreeModel() or verifiFromOutside i'm getting only null objects. Can you please help me understand this behavior? I'll place the code bellow.
package Networking;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class RemoteNetworking extends Thread{
private volatile Socket remoteSocket;
private volatile boolean isRunning = true;
private Thread currentThread;
private volatile ObjectOutputStream oos;
private volatile ObjectInputStream ois;
private volatile DefaultTreeModel treeModel = null;
private String IP;
private int port;
private static volatile String test;
public RemoteNetworking(String IP, int port) {
this.IP = IP;
this.port = port;
}
public void connect() {
try {
SocketAddress socketAddress = new InetSocketAddress(IP, port);
remoteSocket = new Socket();
remoteSocket.connect(socketAddress);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private synchronized void setReceivedTreeModel(DefaultTreeModel receivedTreeModel) {
this.treeModel = receivedTreeModel;
}
public synchronized void disconnect() {
try {
//oos.writeObject("Disconnect");
oos.flush();
//oos.close();
isRunning = false;
remoteSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized DefaultTreeModel getClientTreeModel() {
return treeModel;
}
public synchronized void verifyFromOutside() {
System.out.println(test);
}
#Override
public void run() {
connect();
synchronized(this) {
this.currentThread = Thread.currentThread();
}
try {
ois = new ObjectInputStream(remoteSocket.getInputStream());
oos = new ObjectOutputStream(remoteSocket.getOutputStream());
oos.writeObject("DataTree");
oos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(isRunning) {
try {
Object object = (Object)ois.readObject();
/*if(object instanceof DefaultTreeModel) {
//this received object is not null
setReceivedTreeModel((DefaultTreeModel)object);
if(treeModel==null) {
System.out.println("Null object in RemoteNetworking");
}
verifyFromOutside();
}*/
if(object instanceof String) {
this.test = (String)object;
System.out.println(test);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Java Properties class bug

I have this piece of code.
// On a thread
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path directory = Paths.get("properties");
WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
for (WatchEvent<?> event : watchKey.pollEvents()) {
Path changed = (Path) event.context();
if (changed.toString().equals("radar.properties")) {
System.out.println("read call:");
readProperties();
}
}
if (!watchKey.reset()) {
break;
}
}
} catch (IOException e) {
FCSLogger.LOGGER.log(Level.SEVERE, "Exception while setting up WatchService", e);
}
// Method called by the above code
private void readProperties() {
try {
InputStream input = new FileInputStream(Paths.get("properties", "radar.properties").toString());
Properties prop = new Properties();
prop.load(input);
updateRate = Integer.parseInt(prop.getProperty("updateRate"));
System.out.println(updateRate);
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It returns the right result on the first call and then blocks the whole thread. I've isolated the bug to be in this method since everything else works flawlessly when there is no calling this method. I'm wondering what am I doing wrong here.
Snapshot of console output:
// First change of file:
read call:
10
read call:
10
// Second change of file:
read call:
// I keep changing but nothing happens:
It can be that readProperties throws NumberFormatException, and that causes your watcher thread to exit.
You could wrap calls to readProperties and catch exceptions; so that at least the watcher will keep watching in case of exceptions.
And you should use take, so that the watcher thread blocks. Your current solution causes 100% cpu usage.
See below the modified code. I added a writer thread to update the file, and (unsurprisingly?) readProperties can fail since we are accessing the file while it is being written. A possible output is:
....
property=5000
property=null
java.lang.NumberFormatException: null
at java.base/java.lang.Integer.parseInt(Integer.java:614)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at cl.ClientPoll.readProperties(ClientPoll.java:26)
at cl.ClientPoll.run(ClientPoll.java:46)
property=6000
property=7000
....
So when watching, you can either: skip on error and continue; or use other APIs so that the file being written is locked while writing.
Sample code
package cl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Properties;
public class ClientPoll extends Thread {
private void readProperties() {
try {
Path path = Paths.get("radar.properties");
InputStream input =new FileInputStream(path.toString());
Properties prop = new Properties();
prop.load(input);
String property = prop.getProperty("updateRate");
System.out.println("property="+property);
int updateRate = Integer.parseInt(property);
// System.out.println(updateRate);
input.close();
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
#Override
public void run() {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path directory = Paths.get(".");
WatchKey watchKey = directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
WatchKey wk = watcher.take();
for (WatchEvent<?> event : wk.pollEvents()) {
Path changed = (Path) event.context();
if (changed.toString().equals("radar.properties")) {
try {
readProperties();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
if (!watchKey.reset()) {
break;
}
}
} catch (IOException e) {
e.printStackTrace(System.out);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ClientPoll().start();
new Writer().start();
}
}
class Writer extends Thread {
#Override
public void run() {
try {
for (int i=0;i<10;i++) {
File f = new File("radar.properties");
FileWriter fw = new FileWriter(f);
fw.write("updateRate="+i*1000);
fw.close();
sleep(1000L);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
System.out.println("exit");
System.exit(0);
}
}

Java mqtt concurrent connections is taking time

I am trying to make the concurrent session to MQTT server and all clients will disconnect once all the connections are made.
In the below publisher code I am trying to make concurrents sessions each sending 50 messages. And like this 500 threads will create and each will send 50 messages. But for creating 100 connections it is taking 10 minutes. Is there any mistake in coding and is it possible to decrease the rate of connection speed changing in below code, because the same thing I have written in Golang the rate of connection is high there.
Below is the publisher code:
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
public class Publisher extends Thread{
public static final String test_topic = "test";
private MqttClient client;
public static final String BROKER_URL = "tcp://192.168.1.129:1883";
CountDownLatch latch;
public Publisher(CountDownLatch latch) {
super();
this.latch = latch;
}
public void Publisher() {
String clientid=Thread.currentThread().getName();
System.out.println("=========== "+clientid);
MqttConnectOptions options = null;
try {
client = new MqttClient(BROKER_URL, clientid);
options = new MqttConnectOptions();
options.setCleanSession(true);
options.setMaxInflight(50);
client.connect(options);
} catch (MqttException e) {
try {
client.connect(options);
} catch (MqttSecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (MqttException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
//System.exit(1);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
Publisher();
System.out.println(Thread.currentThread().getName());
try {
for(int i=0;i<50;i++)
{
//Thread.sleep(20);
publishTemperature();
}
} catch (MqttPersistenceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /*catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public void publishTemperature() throws MqttPersistenceException, MqttException {
final MqttTopic test = client.getTopic(test_topic);
final String temperature=""{\"test\":\"test\"}"";
test.publish(new MqttMessage(temperature.getBytes()));
//System.out.println("Published data. Topic: " + "test" + " Message: " + temperature);
}
public MqttClient getClient() {
return client;
}
public void setClient(MqttClient client) {
this.client = client;
}
}
Below is the main method:
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
public class test {
static Publisher[] Publisher=null;
public static void main(String[] args) throws MqttPersistenceException, MqttException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(50);
Publisher = new Publisher[500];
for(int i=0;i<500;i++)
{
Thread.sleep(10);
Publisher[i]=new Publisher(latch);
Publisher[i].start();
}
latch.await();
for(int i=0;i<500;i++)
{
//Thread.sleep(10);
Publisher[i].getClient().disconnectForcibly(25);
}
}
}
Here all connections will connect and make persistent connection up to reaching 500 connections. After that, all connections will disconnect once.
Remove the following line:
Publisher[i].join();
The docs for Thread.join() say the following:
public final void join()
throws InterruptedException
Waits for this thread to die.
An invocation of this method behaves in exactly the same way as the
invocation
join(0)
This means that every time round the loop it will stop and wait for that thread to complete it's task before creating the new one.
If you remove that call it will allow all the threads to run in parallel.

KnockKnockServer in Java

I am newbie in java networking ,I am trying to make a server application in java called instant messaging without GUI. So whenever i run the program it says
" Main method not found in class Methods, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application" -ECLIPSE
Please help me what's wrong in my code.
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
// FIRST FILE //
public class main{
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
}
//SECOND FILE//
public class Server {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//wait For Connection,then display connection information
private void waitforConnection() {
System.out.println("wait for Someone to Connect.....\n");
try {
connection=server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error In Acceptance of Server!!\n...");
}
System.out.println(("Connection Established"+connection.getInetAddress().getHostName()));
}
//Setting Up Streams to Get Input and Output
private void setupStreams(){
try {
output=new ObjectOutputStream(connection.getOutputStream());
output.flush();
input=new ObjectInputStream(connection.getInputStream());
System.out.println("Your Streams are Perfectly Working...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error Found! in Streaming Connectionos");
e.printStackTrace();
}
}
// While Chatting Method....!!//
private void whileChatting() throws IOException{
String Message="You are now Connected!!\n";
sendMessage(Message);
//abletoType(true);
do{
try{
Message=(String) input.readObject();
System.out.println("\n"+Message);
}
catch(ClassNotFoundException e ){
System.out.println("wtf---Fuck\n YOu\n Bloody\n HAcker!!!\n");
}
}
while(!Message.equals("CLIENT--END"));
}
// Closing All Streams and Socket after you are done//
private void closeCrap(){
System.out.println("\nClosing Connection...........Bye Bye\n");
//abletoType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Couldn't Close Connections!");
}
}
//Sending Messages to Client
private void sendMessage(String message){
try {
output.writeObject("SERVER--- "+message);
output.flush();
System.out.println("\nServer- "+message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Dude I cant Send yeaah..");
}
}
// Setting up the Server
public void runningserver(){
try {
server=new ServerSocket(4444,100);
while(true){try{
//connect and Have connection
waitforConnection();
setupStreams();
whileChatting();
}
finally{
closeCrap();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT: Here is the solution and I checked it and for me it works (run the MainClass.java file!):
//MainClass.java file:
public class MainClass {
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
}
//Server.java file:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
// wait For Connection,then display connection information
private void waitforConnection() {
System.out.println("wait for Someone to Connect.....\n");
try {
connection = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("error In Acceptance of Server!!\n...");
}
System.out.println(("Connection Established" + connection
.getInetAddress().getHostName()));
}
// Setting Up Streams to Get Input and Output
private void setupStreams() {
try {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
System.out.println("Your Streams are Perfectly Working...");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Error Found! in Streaming Connectionos");
e.printStackTrace();
}
}
// While Chatting Method....!!//
private void whileChatting() throws IOException {
String Message = "You are now Connected!!\n";
sendMessage(Message);
// abletoType(true);
do {
try {
Message = (String) input.readObject();
System.out.println("\n" + Message);
} catch (ClassNotFoundException e) {
System.out.println("wtf---Fuck\n YOu\n Bloody\n HAcker!!!\n");
}
} while (!Message.equals("CLIENT--END"));
}
// Closing All Streams and Socket after you are done//
private void closeCrap() {
System.out.println("\nClosing Connection...........Bye Bye\n");
// abletoType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Couldn't Close Connections!");
}
}
// Sending Messages to Client
private void sendMessage(String message) {
try {
output.writeObject("SERVER--- " + message);
output.flush();
System.out.println("\nServer- " + message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Dude I cant Send yeaah..");
}
}
// Setting up the Server
public void runningserver() {
try {
server = new ServerSocket(4444, 100);
while (true) {
try {
// connect and Have connection
waitforConnection();
setupStreams();
whileChatting();
} finally {
closeCrap();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I can run that without an exception.
The Problem is your main method
public static void main (String[] args) {}
Is not in the class where you run it.
//separate file A.java
public class A
{}
//separate file B.java
public class B
{
public static void main (String[] args) {}
}
If you now run B, it works, because B.java has a main method. BUT: if you run A.java it says:
no main methode found. The file you want to run (A, B, etc. must have a main method defined)
If you run a java file, it will look for a main method (start point of execution).
The main method must be a method of the class:
import java.net.Socket;
public class Server {
public static void main (String[] args) {
Server s=new Server();
s.runningserver();
}
So it must come after the class declaration.

JVM does not exit when TimeoutException occurs

I have code which needs to do something like this
There is a list of classes each with some method (lets say execute()). I need to invoke that method on each class and there is a fixed timeOut for each invocation. Now, one of the class's execute method is badly written and results in a timeout due to which the jvm does not exit. I am running the class like this.
java ExecutorServiceTest execute TestClass1 TestClass2 TestClass3
Why does the jvm not exit after completing the execution of the code?
I get the following output
In class 1
In Class 2
java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at ExecutorServiceTest.main(ExecutorServiceTest.java:78)
java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
The second class's execute times out and after that, the third class's execute also times out. Why does the third class's execute time out?
The jvm does not exit after the execution is complete. What is the reason? Also why is the TestClass3 execute timedout?
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
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.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
class Task implements Callable<String> {
Object instance;
Method m;
Object[] input;
Task(Object instance, Method m, Object[] input) {
this.instance = instance;
this.m = m;
this.input = input;
}
public String call() {
String s = "initial";
try {
m.invoke(instance, input);
}
catch (RuntimeException e) {
}
catch (Exception e) {
}
finally {
}
return s;
}
}
public class ExecutorServiceTest {
public static void main(String[] args) {
String methodName = args[0];
String className;
List<Object> instanceList = new ArrayList<Object>();
for (int i=1;i<args.length;i++) {
className = args[i];
Object o = null;
try {
o = Class.forName(className).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
instanceList.add(o);
}
ExecutorService executor = Executors.newSingleThreadExecutor();
Iterator<Object> iter = instanceList.iterator();
while (iter.hasNext()) {
Object o = iter.next();
Method m = null;
try {
m = o.getClass().getDeclaredMethod(methodName, new Class[] {});
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Task t = new Task(o,m,new Object[]{});
Future<String> fut = executor.submit(t);
try {
fut.get(2,TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
executor.shutdown();
}
}
public class TestClass1 {
public void execute() {
System.out.println("In class 1");
}
}
public class TestClass2 {
public void execute() {
System.out.println("In class 2");
boolean b = true;
while (b) {
}
}
}
public class TestClass3 {
public void execute() {
System.out.println("In class 3");
}
}
ExecutorService.shutdown() doesn't actually stop any running executors/threads, it just tells the service to stop accepting new tasks:
void shutdown()
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.
Your TestClass2 instance is never going to stop running because it has a while(true) loop which is never halted.
If you want to stop the ExecutorService immediately, you can use awaitTermination(long timeout, TimeUnit unit) or shutdownNow().
You need to call executor.shutdown() or create a daemon thread (using appropriate ThreadFactory passed to Executors.newSingleThreadExecutor()

Categories