Launching zookeeper in a separate thread - java

I'm trying to launch multiple embedded zookeeper servers into separate threads from a Java application this way:
String port1 = "2181";
String directory1 = new File(System.getProperty("java.io.tmpdir"), "zookeeper/data1").getAbsolutePath();
final ServerConfig config1 = new ServerConfig();
config1.parse(new String[] { port1, directory1 });
new Thread(new Runnable() {
#Override
public void run()
{
try{
ZooKeeperServerMain zk = new ZooKeeperServerMain()
zk.runFromConfig(config1);
}catch(Exception e){
e.printStackTrace();
}
}
}).run();
When I start zk this way, the main process is blocked and the remaining instructions are not executed!
Is there a proper way to launch zookeeper in a separate thread?

You are calling run() instead of start() on your Thread.
new Thread(new Runnable() {
#Override
public void run()
{
try{
ZooKeeperServerMain zk = new ZooKeeperServerMain()
zk.runFromConfig(config1);
}catch(Exception e){
e.printStackTrace();
}
}
}).start();

Related

Thread issue in javafx. Multiple thread are created

I have program with javafx and want to refresh list's with new data when other user's insert data. So program to have real-time data. Problems is with thread i created. Every time i open a view it's create a new thread and have multiple notifications instead of one. I tried to extend class with Thread and with implementing Runnable but i had no success.
On method initialize i have code where i create a runnable and set it to thread.
int i = 0;
Runnable br = new Runnable() {
#Override
public void run() {
while (i < i + 1) {
try {
Thread.sleep(1000);
if (count_pacient_number != pjc.getPacientForDoctor(doctor_login).size()) {
Platform.runLater(new Runnable() {
#Override
public void run() {
emf.getCache().evictAll();
pacientList.clear();
patientList();
count_pacient_number = pjc.getPacientForDoctor(doctor_login).size();
}
});
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
};
// private Thread thread = null; is created on start of class
thread = new Thread(br);
thread.setDaemon(true);
thread.start();

Update Swing GUI from other thread

I have two classes, one of them is my thread in which I read outputs from a device through TCP/IP:
public static controlPanel cp = new controlPanel();
void startListenForTCP (final String ipaddress){
Thread TCPListenerThread;
TCPListenerThread = new Thread(new Runnable() {
#Override
public void run() {
Boolean run = true;
String serverMessage = null;
InetAddress serverAddr = null;
BufferedWriter out = null;
try
(Socket clientSocket = new Socket(ipaddress, 7420)) {
cp.updateGUI("Connection initiated... waiting for outputs!"+"\n");
char[] buffer = new char[2];
int charsRead = 0;
out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while ((charsRead = in.read(buffer)) != -1)
{
String message = new String(buffer).substring(0, charsRead);
switch (message) {
case "o,":
cp.updateGUI("Čekanje da loptica prođe RFID čitač!");
break;
case "y,":
cp.updateGUI("Hardverski problem!");
break;
case "Y,":
cp.updateGUI("Loptica nije izažla, hardverski problem!");
break;
case "I,":
cp.updateGUI("Uređaj u stanju mirovanja!!");
break;
default:
String m = message;
m = m.replaceAll("[^\\d.]", "");
try{
int i = Integer.parseInt(m);
System.out.println("Is int: "+i);
int izasao=Integer.parseInt(m);
if (redni>34){
redni=0;
}
if (izasao>0 && izasao<49){
redni =redni+1;
m=m;
ur.updateResults(redni, m);
bs.testAuto(m, redni);
System.out.println(m+ "\n");
}
} catch(NumberFormatException e){
} break;
}
}}
catch(UnknownHostException e) {
System.out.println("Unknown host..."+"\n");
} catch(IOException e) {
System.out.println("IO Error..."+"\n");
}
}
});
TCPListenerThread.start();
}
The other one is swing form in which i want to set jLabel text from the class above:
Public class controlPanel extends javax.swing.JFrame {
public static gameControler gc = new gameControler();
public controlPanel() {
initComponents();
}
public void updateGUI(final String text) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
updateGUI(text);
}
});
}jLabel5.setText(text);
System.out.println(text);
}
The message gets printed out in console but i can't set it's value to jLabel.
I need a quick way to achieve this, so any workarounds will be most helpfull.
Thank you,
Your code only updates the GUI if current thread is not the EDT:
if (!SwingUtilities.isEventDispatchThread()) {
// you call SwingUtilities.invokeLater();
}
The GUI update should also happen if the current thread happens to be the EDT. So you should change it to somehting like this:
if (SwingUtilities.isEventDispatchThread())
jLabel5.setText(text);
else
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
jLabel5.setText(text);
}
});
Note that invokeLater() is not executed immediately but asynchronously some time later. If you need the update to happen before it returns, use SwingUtilities.invokeAndWait().
Also note that you may consider using the SwingWorker class to perform lengthy GUI-interaction tasks in a background thread.
Making it utility method
If you have to do this many times, it is profitable to make a utilitiy method for this:
public void callFromEdt(Runnable task) {
if (SwingUtilities.isEventDispatchThread())
task.run();
else
SwingUtilities.invokeLater(task); // You might want to consider
// using invokeAndWait() instead
}

Jlayer in a Jpanel with circular loading bar

here is my exemple of making a circular loading bar with Jlayer but now the layer start and stop after the execution of the btnLoad.addActionListener() and stop after a while of determinated timer (4000) so my problem that I need it to start when I click the button load
and stop after complete the loading of the file !!!
final WaitLayerUI layerUI = new WaitLayerUI();
jlayer = new JLayer<JPanel>(this, layerUI);
final Timer stopper = new Timer(4000,new ActionListener() {
public void actionPerformed(ActionEvent ae) {
layerUI.stop();
}
});
stopper.setRepeats(false);
if (!stopper.isRunning()) {
stopper.start();
}
btnLoad.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
layerUI.start();
DataManager dataManager = new DataManager();
try {
dataManager.loadFromFile("C:/Users/*****PC/Downloads/****.csv");
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
You should load the file on another Thread and not the Event Dispatch Thread. Assuming your loadFromFile method blocks until it loads the file, you can then hide the layer, but you must hide on the Event Dispatch Thread and not the new Thread you started for loading the file.
Remove your timer and replace your try block with this:
try {
new Thread(new Runnable(){
public void run() {
dataManager.loadFromFile("C:/Users/*****PC/Downloads/****.csv");
EventQueue.invokeLater(new Runnable(){
public void run() {
layerUI.stop();
}
});
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}

Text Area not getting updated with the button action performed event

I have a Text Area swing element where I want to display some execution logs. messages should appear after each execution step. e.g. "Fetching has been started". But the problem is that all logs messages appear only once after the button action performed event is completed.Below is the way I used to display some text
getXmlButton = new JButton("Fetch Reports");
getXmlButton.addActionListener((new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
createDirectory();
stutusArea.append("Fetching has been started");
final String password = passwordTextField.getText();
final String username = loginTextField.getText();
OperatingSystemDriver os = new OperatingSystemDriver();
driver = os.getDriver();
stutusArea.append("getting some url");
driver.get(URL);
try {
LoginPage login = new LoginPage(driver);
login.loginAs(username, password);
stutusArea.append("successful login");
} catch (Exception e1) {
stutusArea.append("login error");
}
insertToDbButton.setEnabled(true);
}
}));
You have to use a different thread, otherwise your GUI blocks.
Please note that updating the GUI from an other thread is a bad idea, use SwingUtilities.invokeLater to avoid some strange errors/bugs.
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
stutusArea.append("Fetching has been started");
}
})
final String password = passwordTextField.getText();
final String username = loginTextField.getText();
// ...
}
}).start();
}
That's because you do all your ActionPerformed stuff in the GUI thread, so the GUI freezes, and waits for your ActionPerformed stuff to be done, a way to avoid this is using Threads, there is an example: Thread Example

Handle socket termination in android

I am connected to a device using following code.
Using this socket code I cam perfom all the tasks, but now I need to perform some functions when server is going to be down. I am not able to find suitable method to do so please help.
EDIT
I want to detect when server is disconnected with this client , means after doing transactions server will be disconnected so that i can disable the buttons ,
void sendRequest(){
try {
this.clientSocket=new Socket("192.168.1.11",2000);
this.os=new DataOutputStream(this.clientSocket.getOutputStream());
this.in=new DataInputStream(this.clientSocket.getInputStream());
sendFirtCommand();
Client t=new Client();
t.start();
}catch(Exception e){
e.printStackTrace();
}
}// end of the sendRequest
My Thread code
private class Client extends Thread{
int time;
public void run(){
try{
while(true){
//if(in.read()==-1) break;
int size =in.available();
if(size>0){
byte data[]=new byte[size];
in.readFully(data);
String str=new String(data);
// System.out.println(data);
//char c[]=str.toCharArray();
str=toHex(data);
System.out.println(str);
/*
if(str.equalsIgnoreCase("050D00E7F0E1000101581D4A1D01FF")){
System.out.println("Start Left 3");
}
*/
if(str.equalsIgnoreCase("050d00e7f0e1000101601d4a1d01ff")){
stopAll();
handler.post(new Runnable() {
#Override
public void run() {
enableAll();
}
});
}
}
Try this if it helps
try{
while(true){
if(str.equalsIgnoreCase("050d00e7f0e1000101601d4a1d01ff")){
stopAll();
handler.post(new Runnable() {
#Override
public void run() {
enableAll();
}
});
}
}
}catch(IOException e)
{
handler.post(new Runnable() {
#Override
public void run() {
enableAll();
}
});
}
It seems as if Exception handling is not there in the code you have posted, let me know if i am missing something ...

Categories