Java Vector<E> getting blocked with no apparent reason - java

I'm probably doing something wrong, but this is what happens:
I register a listener, wait for it to be called and when it executes and calls "Vector.clear()" it locks. The problem happens in the "pipeMsgEvent" method, here it is the, not so friendly-looking, code (if you want, go directly to "this is important" lines):
public class JxtaCustomer implements PipeMsgListener {
public static final int ANSWER_OK = 0;
public static final int ANSWER_TIMEOUT =-1;
public static final int ANSWER_NOT_ASKED =-2;
public static final int ANSWER_WORKING =-3;
public static final int REQ_SENT = 0;
public static final int REQ_INV_PIPE_ID =-1;
public static final int REQ_INV_PIPE_IO =-2;
public static final int REQ_INV_GROUP_ID =-3;
protected int answer;
protected JxtaGenericAdvertisement serviceAdv = null;
protected JxtaNode ThePeer = null;
JxtaBiDiPipe myBiDiPipe = null;
protected Vector<Entry> output = null;
public JxtaCustomer(JxtaGenericAdvertisement adv, JxtaNode peer)
{
ThePeer = peer;
serviceAdv = new JxtaGenericAdvertisement((Element)adv.getDocument(new MimeMediaType("text/xml")));
answer = ANSWER_NOT_ASKED;
Vector<Entry> output = new Vector<Entry>();
}
public void pipeMsgEvent(PipeMsgEvent event)
{
System.out.println("It Works! Uhuuu");
// We received a message
Message message = event.getMessage();
System.out.println("Lets GO! Uhuuu");
Message.ElementIterator elIt = message.getMessageElementsOfNamespace( serviceAdv.getName() );
System.out.println("A little bit more");
answer = ANSWER_WORKING;
System.out.println("enter");
// This is important: Here I get stuck, "clear"
// never appears on the screen
output.clear();
System.out.println("clear");
while (elIt.hasNext()) {
MessageElement mElem = elIt.next();
System.out.println(mElem.getElementName() + " " + mElem.toString());
output.add( new Entry( mElem.getElementName(), mElem.toString() ) );
}
System.out.println("leave");
answer = ANSWER_OK;
}
public int sendRequest(Vector<Entry> params)
{
try {
// Creating Pipe Advertisement
String pipeAdvType = PipeAdvertisement.getAdvertisementType();
PipeAdvertisement pipeAd = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(pipeAdvType);
URI pipeURI = new URI(serviceAdv.getPipeID());
pipeAd.setPipeID( IDFactory.fromURI(pipeURI) );
pipeAd.setType(PipeService.UnicastType);
pipeAd.setName(serviceAdv.getName() + " Service Pipe");
pipeAd.setDescription("Created by " + serviceAdv.getName());
// Creating Group
JxtaGroup jxgp = ThePeer.getGroupFromID( serviceAdv.getGroupID() );
if (null == jxgp)
return REQ_INV_GROUP_ID;
PeerGroup group = jxgp.getPeerGroup();
if (null == group)
return REQ_INV_GROUP_ID;
// This is important: In the JxtaBiDiPipe call I register
// the callback, while I have access to the code, I think
// the problem is in my code
myBiDiPipe = new JxtaBiDiPipe( group, pipeAd, 30000, this);
if (myBiDiPipe.isBound()) {
Thread.sleep(500);
Message myMessage = new Message();
if (0 == params.size())
params.add( new Entry("dummy", "null") );
for (int i=0; i<params.size(); i++) {
String Key = params.get(i).getKey();
String Value = params.get(i).getValue();
StringMessageElement strMsgElem = new StringMessageElement( Key, Value, null);
myMessage.addMessageElement( serviceAdv.getName(), strMsgElem);
}
myBiDiPipe.sendMessage(myMessage);
answer = ANSWER_TIMEOUT;
return REQ_SENT;
}
} catch (URISyntaxException e){
e.printStackTrace();
return REQ_INV_PIPE_ID;
} catch (IOException e) {
return REQ_INV_PIPE_IO;
} catch (Exception e) {
e.printStackTrace();
}
return REQ_INV_PIPE_IO;
}
public Vector<Entry> getResponse()
{
Vector<Entry> results = new Vector<Entry>();
if (ANSWER_OK != answer)
return results;
// This is important: I always call "getState()" and check its value
// before calling this method, so you can say it's guaranteed to be
// called after answer = ANSWER_OK, which never happens because of the
// lock
for (int i=0; i<output.size(); i++)
results.add( output.get(i) );
return results;
}
public int getState()
{
int count = 10;
return answer;
}
}
I always create JxtaCustomer like this:
JxtaCustomer customer = new JxtaCustomer(adv, ThePeer);
Vector<Entry> params = new Vector<Entry>();
params.add( new Entry("key1", "value1") );
params.add( new Entry("key2", "value2") );
customer.sendRequest(params);
while(JxtaCustomer.ANSWER_OK != customer.getState()) {
// I was actually using synchronized locks and timed waits
// but since I'm stuck there I'm using this nonsense instead
}
Vector<Entry> response = customer.getResponse();
Here is where in the code I call "sleep", "wait" or I create a "synchronized" (this last one is never)
$ grep synchronized $(find . -name "*.java")
$ grep sleep $(find . -name "*.java")
./Src/net/ubi/jxta/JxtaCustomer.java: Thread.sleep(500);
$ grep wait $(find . -name "*.java")
./App/ExampleServices/SimpleSigner.java: boolean waiting = false;
./App/ExampleServices/SimpleSigner.java: waiting = true;
./App/ExampleServices/SimpleSigner.java: return (waiting && JxtaCustomer.ANSWER_OK == customer.getState());
./App/ExampleServices/SimpleSigner.java: if (!waiting)
./App/ExampleServices/SimpleSigner.java: waiting = false;
./App/ExampleServices/SimpleSigner.java: return "Error: Response not ready, wait more time\n";

Your constructor sets a local variable called output,and not the member variable, you have
Vector<Entry> output = new Vector<Entry>();
when it should be
output = new Vector<Entry>();
So, later on when you call output.clear() you're getting an Null Pointer Exception thrown, which is why the following lines of code don't get executed.
compiler warnings like "unused local variables" can help spot these sorts of mistakes.

Related

Why is my Java Program returning only the last String in an ArrayList

I want my Java Program to return a String response based on if/else conditions but it only responds to the last element in the ArrayList.
I have been working on this for two days without success.
I will appreciate a direction as to what am doing wrongly. Thank You
import java.io.IOException;
import java.util.logging.Logger;
public class ScanUtility implements IScanUtility {
Logger logger = Logger.getLogger("ScanUtility");
private String performHostScan(String nodeName) {
Process OSCmdProcess = null;
Integer exitValue = null;
String OScmd = null;
String exitMessage = null;
String OScmd = new String("/usr/bin/ssh ansible#" + nodeName + " " + "/tmp/openscapscan.bash rheldisa");
try {
OSCmdProcess = Runtime.getRuntime().exec(OScmd);
exitValue = OSCmdProcess.waitFor();
if (exitValue.equals(0)) {
exitMessage = ("Succeeded on" + " " + nodeName);
return exitMessage;
} else {
exitMessage = ("Failed on" + " " + nodeName);
return exitMessage;
}
} catch (IOException ioExcep) {
ioExcep.printStackTrace();
} catch (InterruptedException interExcep) {
interExcep.printStackTrace();
}
return exitMessage;
}
//This method takes an ArrayList of hosts from the servlet controller
// and passes the list to the ScanUtility Method above
//============================================================
public String generateHostName(List<String> addressList){
String statusMessage = null;
for(String nodeName: addressList){
statusMessage = new ScanUtility().performHostScan(nodeName);
}
return statusMessage;
}
}
The problem is that you are overwriting statusMessage on ever iteration of your loop. I believe what you want to do is put all the Strings into an ArrayList<String>.
public ArrayList<String> generateHostName(List<String> addressList){
ArrayList<String> statusMessage = new ArrayList<>();
for(String nodeName: addressList){
statusMessage.add(new ScanUtility().performHostScan(nodeName));
}
return statusMessage;
}
Apparently, you want to return a list of status messages (a status message from each server that you are scanning).
public List<String> getResponsesFromAddresses(List<String> addresses) {
final ScanUtility scanUtility = new ScanUtility();
return addresses.stream()
.map(scanUtility::performHostScan)
.collect(Collectors.toList());
}
The method name is misleading. I have changed it to getResponsesFromAddresses - that is what the method actually does.
Try this:
public List<String> generateHostName(List<String> addressList){
List<String> statusMessages = new ArrayList<>();
for(String nodeName: addressList){
statusMessages.add(new ScanUtility().performHostScan(nodeName));
}
return statusMessages;
}

How to create two instances of the same method with different parameters

I need to create 2 instances that run the same SQL procedure but with different parameters.
public void run() {
// TRUE if there is no more VER_STOCK
boolean booEsgotado = false;
System.out.println("Starting thread" + numThread );
try {
objLigacao = DriverManager.getConnection(LIGACAO,
UTILIZADOR, SENHA);
// manual control of transactions
objLigacao.setAutoCommit(false);
while (booEsgotado == false && i<=5) {
try {
objComando = objLigacao.prepareCall(INSERE);
// 1 = first parameter (:1)
objComando.setInt(1, ID);
objComando.setInt(2, PRODUTO);
objComando.setInt(3, Q);
objComando.execute();
objComando.close();
// If done with success commit the operations
objLigacao.commit();
i++;
System.out.println("Sold a unit in thread " + numThread + " i = " + i);
objComando = objLigacao.prepareCall(QUANT);
objComando.setInt(1, PRODUTO);
objResultado = objComando.executeQuery();
while(objResultado.next()) {
stock=objResultado.getInt(1);}
System.out.println("Stock atual=" + stock);
}
catch (SQLException objExcepcao) {
System.out.println("" + objExcepcao.getMessage());
// If something failed rollback the operations
objComando.close();
objLigacao.rollback();
booEsgotado = true;
System.out.println("Product is out of stock in thread" + numThread);
}
}
// Libertação de recursos.
objLigacao.close();
} catch (SQLException objExcepcao) {
System.out.println(objExcepcao.getMessage());
}
System.out.println("The end of thread " + numThread );
}
The thing is that I can only run the same procedure with the same arguments in both instances. Where I need to execute the same procedure but with different arguments in both instances.
runne1 objInstancia1 = new runne1(1);
runne1 objInstancia2 = new runne1(2);
// Create a thread for each instance
Thread objThread1 = new Thread(objInstancia1);
Thread objThread2 = new Thread(objInstancia2);
objThread1.start();
objThread2.start();
try {
objThread1.join();
objThread2.join();
Subclass Thread to provide a constructor that specifies parameters you need and store them as instance fields.
In this way, you could use them in the run() method.
public class MyCallThread extends Thread {
private int paramOne;
private int paramTwo;
public MyCallThread (Runnable runnable, int paramOne, int paramTwo){
super(runnable);
this.paramOne = paramOne;
this.paramTwo = paramTwo;
}
public void run(){
...
objComando.setInt(1, paramOne);
...
}
}
And instantiate it like that :
int paramOne = ...;
int paramTwo = ...;
Thread objThread1 = new MyCallThread(objInstancia1, paramOne, paramTwo);
...

detect concurrent access to syncronized function java

I Have a multithreaded environment in android app. I use a singleton class to store data. This singleton class contains a arraylist that is accessed using a synchronized method.
The app uses this arraylist to render images in app.
Initial problem : Concurrent modification error use to come so I made the get arraylist function syncronized.
Current Problem:Concurrent modification error not coming but in between empty arraylist returned (maybe when there is concurrent access).
Objective : I want to detect when Concurrent modification so that Instead of empty arraylist being return I can return last state of the arraylist.
public synchronized List<FrameData> getCurrentDataToShow() {
List<FrameData> lisCurrDataToShow = new ArrayList<FrameData>();
//for (FrameData fd : listFrameData) {//concurrent modification exception
//todo iterator test
Iterator<FrameData> iterator = listFrameData.iterator();
while (iterator.hasNext()) {
FrameData fd = iterator.next();
long currentTimeInMillis = java.lang.System.currentTimeMillis();
if ((currentTimeInMillis > fd.getStartDate().getTime() && currentTimeInMillis < fd.getEndDate().getTime()) || (fd.isAllDay() && DateUtils.isToday(fd.getStartDate().getTime()))) {
if (new File(ImageFrameActivity.ROOT_FOLDER_FILES + fd.getFileName()).exists()) {
lisCurrDataToShow.add(fd);
}
}
}
if (lisCurrDataToShow.size() == 0) {
lisCurrDataToShow.add(new FrameData(defaultFileName, null, null, null, String.valueOf(120), false));
}
return lisCurrDataToShow;
}
Referred to Detecting concurrent modifications?
Please help!
EDIT1:
This problem occurs rarely not everytime.
If a threads is accessing getCurrentDataToShow() and another thread tries to access this function what will the function return?? I'm new to multithreading , please guide
Edit 2
in oncreate following methods of singleton are called periodically
DataModelManager.getInstance().getCurrentDataToShow();
DataModelManager.getInstance().parseData(responseString);
Complete singleton class
public class DataModelManager {
private static DataModelManager dataModelManager;
private ImageFrameActivity imageFrameAct;
private String defaultFileName;
public List<FrameData> listFrameData = new ArrayList<FrameData>();
// public CopyOnWriteArrayList<FrameData> listFrameData= new CopyOnWriteArrayList<FrameData>();
private String screensaverName;
private boolean isToDownloadDeafultFiles;
private String tickerMsg = null;
private boolean showTicker = false;
private boolean showHotspot = false;
private String hotspotFileName=null;
public String getDefaultFileName() {
return defaultFileName;
}
public boolean isToDownloadDeafultFiles() {
return isToDownloadDeafultFiles;
}
public void setToDownloadDeafultFiles(boolean isToDownloadDeafultFiles) {
this.isToDownloadDeafultFiles = isToDownloadDeafultFiles;
}
private String fileNames;
private DataModelManager() {
}
public static DataModelManager getInstance() {
if (dataModelManager == null) {
synchronized (DataModelManager.class) {
if (dataModelManager == null) {
dataModelManager = new DataModelManager();
}
}
}
return dataModelManager;
}
private synchronized void addImageData(FrameData frameData) {
//Log.d("Frame Data","Start date "+frameData.getStartDate()+ " " +"end date "+frameData.getEndDate());
listFrameData.add(frameData);
}
public synchronized void parseData(String jsonStr) throws JSONException {
listFrameData.clear();
if (jsonStr == null) {
return;
}
List<String> listFileNames = new ArrayList<String>();
JSONArray jsonArr = new JSONArray(jsonStr);
int length = jsonArr.length();
for (int i = 0; i < length; i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
dataModelManager.addImageData(new FrameData(jsonObj.optString("filename", ""), jsonObj.optString("start", ""), jsonObj.optString("end", ""), jsonObj.optString("filetype", ""), jsonObj.optString("playTime", ""), jsonObj.optBoolean("allDay", false)));
listFileNames.add(jsonObj.optString("filename", ""));
}
fileNames = listFileNames.toString();
}
public void setDefaultFileData(String jsonStr) throws JSONException {
JSONObject jsonObj = new JSONObject(jsonStr);
defaultFileName = jsonObj.optString("default_image", "");
screensaverName = jsonObj.optString("default_screensaver ", "");
}
#Override
public String toString() {
return fileNames.replace("[", "").replace("]", "") + "," + defaultFileName + "," + screensaverName;
}
public FrameData getFrameData(int index) {
return listFrameData.get(index);
}
public synchronized List<FrameData> getCurrentDataToShow() {
List<FrameData> lisCurrDataToShow = new ArrayList<FrameData>();
// for (FrameData fd : listFrameData) {//concurrent modification exception
//todo iterator test
Iterator<FrameData> iterator = listFrameData.iterator();
while (iterator.hasNext()) {
FrameData fd = iterator.next();
long currentTimeInMillis = java.lang.System.currentTimeMillis();
if ((currentTimeInMillis > fd.getStartDate().getTime() && currentTimeInMillis < fd.getEndDate().getTime()) || (fd.isAllDay() && DateUtils.isToday(fd.getStartDate().getTime()))) {
if (new File(ImageFrameActivity.ROOT_FOLDER_FILES + fd.getFileName()).exists()) {
lisCurrDataToShow.add(fd);
}
}
}
if (lisCurrDataToShow.size() == 0) {
lisCurrDataToShow.add(new FrameData(defaultFileName, null, null, null, String.valueOf(120), false));
}
return lisCurrDataToShow;
}
public String getCurrentFileNames() {
String currFileNames = "";
List<FrameData> currFrameData = getCurrentDataToShow();
for (FrameData data : currFrameData) {
currFileNames += "," + data.getFileName();
}
return currFileNames;
}
public ImageFrameActivity getImageFrameAct() {
return imageFrameAct;
}
public void setImageFrameAct(ImageFrameActivity imageFrameAct) {
this.imageFrameAct = imageFrameAct;
}
}
This is the only part of your question that is currently answerable:
If a threads is accessing getCurrentDataToShow() and another thread tries to access this function what will the function return?
It depends on whether you are calling getCurrentDataToShow() on the same target object; i.e. what this is.
If this is the same for both calls, then the first call will complete before the second call starts.
If this is different, you will be locking on different objects, and the two calls could overlap. Two threads need to lock the same object to achieve mutual exclusion.
In either case, this method is not changing the listFrameData collection. Hence it doesn't matter whether the calls overlap! However, apparently something else is changing the contents of the collection. If that code is not synchronizing at all, or if it is synchronizing on a different lock, then that could be a source of problems.
Now you say that you are not seeing ConcurrentModificationException's at the moment. That suggests (but does not prove) that there isn't a synchronization problem at all. And that suggests (but does not prove) that your current problem is a logic error.
But (as I commented above) there are reasons to doubt that the code you have shown us is an true reflection of your real code. You need to supply an MVCE if you want a more definite diagnosis.

File Logger for android apps

I want the simplest logger there is to simply log errors, mostly exceptions, to a Log file in the android file system. for exemple, the easiest and most convinient (in my opinion at least) way that i used to log to a file on PC java was by simply printing all exceptions to console and redirecting system out to both console and my file, this doesnt really suffice on android as far as i know i guess its because of how Android OS is designed, so what is the simplest way of doing it in Android?
Note that the project has already lot of code in it and i really wouldnt like to go over it and add log calls on catch blocks or whatever to log my exceptions, as little i need to do for logging those exceptions is best for my use case...
Thanks ahead!
It's not finished but works quite stable. It saves human readable json array with exception name, time, stack trace and additional data. Also you can save logcat's logs.
Using:
ExceptionWriter ew = new ExceptionWriter(new File(Environment.getExternalStorageDirectory(), "debug.txt"));
ew.w(new IllegalArgumentException("some msg"), "additional message");
Source:
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* User: elevenetc
* Date: 10/9/13
* Time: 12:52 PM
*/
public class ExceptionWriter {
private final StringBuilder sb;
private final ExceptionWriter.WriteExceptionTask writeExceptionTask;
private final SimpleDateFormat dataFormat;
private int totalExceptions;
private StringBuilder stackBuilder = new StringBuilder();
public int getTotalExceptions(){return totalExceptions;}
public ExceptionWriter(File file) throws IOException {
if(file != null){
writeExceptionTask = new WriteExceptionTask(file);
sb = new StringBuilder();
dataFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
new Thread(writeExceptionTask).start();
}else{
sb = null;
writeExceptionTask = null;
dataFormat = null;
}
}
public synchronized int wLogcat(){
try {
writeExceptionTask.addStreamToRead(Runtime.getRuntime().exec("logcat -d -v time").getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public int w(Exception debugException, String caughtMessage){
return w(debugException, caughtMessage, null);
}
public synchronized int w(Exception debugException, String caughtMessage, String additionalData){
if(writeExceptionTask == null) return -1;
sb.setLength(0);
StackTraceElement[] stackTrace = debugException == null ? null : debugException.getStackTrace();
sb.append("{\"date\":\"");sb.append(getTime());
sb.append("\",\"exceptionClassName\":\"");sb.append(debugException == null ? null : debugException.getClass());
sb.append("\",\"exceptionMessage:\":\"");sb.append(debugException == null ? null : debugException.getMessage());
sb.append("\",\"caughtMessage:\":\"");sb.append(caughtMessage);
if(additionalData != null) {sb.append("\",\"data:\":\"");sb.append(additionalData);}
sb.append("\",\"stack\":");sb.append(stackToString(stackTrace));
sb.append("},");
writeExceptionTask.stringQueue.add(sb.toString());
totalExceptions++;
return 0;
}
public void destroy() {
if(writeExceptionTask != null) {
writeExceptionTask.stop();
}
}
private String getTime(){
return dataFormat.format(System.currentTimeMillis());
}
private String stackToString(StackTraceElement[] stackTrace){
if(stackTrace == null) return null;
stackBuilder.setLength(0);
stackBuilder.append("[");
for (int i = 0; i < stackTrace.length; i++) {
StackTraceElement e = stackTrace[i];
stackBuilder.append("{\"");
stackBuilder.append(e.getLineNumber());
stackBuilder.append("\":\"");
stackBuilder.append(e.getClassName());
stackBuilder.append(".");
stackBuilder.append(e.getMethodName());
stackBuilder.append("\"}");
if(i != stackTrace.length -1) stackBuilder.append(",");
}
stackBuilder.append("]");
return stackBuilder.toString();
}
///////////////////////////////////////////////
/// Static classes
///////////////////////////////////////////////
private class WriteExceptionTask implements Runnable {
private final File file;
private boolean running;
private final ConcurrentLinkedQueue<String> stringQueue;
private final ConcurrentLinkedQueue<InputStream> isQueue;
private final FileWriter writer;
private WriteExceptionTask(File file) throws IOException {
this.file = file;
writer = new FileWriter(this.file, true);
stringQueue = new ConcurrentLinkedQueue<String>();
isQueue = new ConcurrentLinkedQueue<InputStream>();
running = true;
}
public void addStreamToRead(InputStream is){
if(is != null){
isQueue.add(is);
}
}
#Override
public void run() {
while(running){
if(!stringQueue.isEmpty()){
//TODO check file existence
try {
writer.append(stringQueue.poll());
writer.flush();
} catch (IOException e) {
e.printStackTrace();
running = false;
}
}
if(!isQueue.isEmpty()){
InputStream is = isQueue.poll();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder("{\"catLog\":\"");
String aux;
try {
while ((aux = reader.readLine()) != null) {
//TODO view like array or \n
builder.append(aux);
}
} catch (IOException e) {
e.printStackTrace();
}
builder.append("\"},");
stringQueue.add(builder.toString());
}
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
running = false;
}
}
}

thread.run() works and thread.start() not works

Following is my main class.
public class ShareData {
/**
* #param args
*/
public static void main(String[] args) {
ShareReader aShareReader = new ShareReader("http://test.com:9000", "dilip.id#gmail.com", "password");
Thread fileThread = new Thread(aShareReader);
fileThread.run(); // fileThread.start() not calling the run() method
}
}
If I type fileThread.run() run method is called. If I call fileThread.start() the run metod is not called. Following is my thread class. I dont know what I am doing wrong.
public class ShareReader implements Runnable {
private String itsShareURL = null;
private String itsUserId = null;
private String itsPassword = null;
private String itsAuthToken = null;
private String itsLoginURL = null;
private String itsChannelUpateURL = null;
/**
*
*/
public ShareReader(String theShareURL, String theUserId, String thePassword) {
this.itsShareURL = theShareURL;
this.itsUserId = theUserId;
this.itsPassword = thePassword;
this.itsLoginURL = itsShareURL + "/v1.0-SNAPSHOT/login";
this.itsChannelUpateURL = itsShareURL + "/v1.0-SNAPSHOT/updateChannelSubscription/";
}
public void run() {
JSONObject json;
JSONArray jsonArray;
itsAuthToken = getToken(itsUserId, itsPassword);
updateChannelList(itsAuthToken);
String aURL = "http://test.com:9000/v1.0-SNAPSHOT/userTimeline/"+itsAuthToken+"/";
try {
String lat = null;
String lon = null;
String udid = null;
String dateTime = null;
String eventID = null;
aEventBean = new EventBean();
jsonArray = readJsonArrayFromUrl(aURL);
for (int i = 0; i < jsonArray.length(); i++) {
json = jsonArray.getJSONObject(i);
lat = json.getString("lat");
lon = json.getString("lon");
udid = json.getString("udid");
eventID = json.getString("eventId");
dateTime = json.getString("dateTime");
aEventBean.setItsLatitude(lat);
aEventBean.setItsLongitude(lon);
aEventBean.setItsUDID(udid);
aEventBean.setItsEventIdentifier(eventID);
aEventBean.setItsDateTime(dateTime);
System.out.println(udid + " ---> " +lat + " ==== " + lon);
sendData(aEventBean);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sorry If I ask so basic question..
Ideally I need to do fileThread.start() to start a thread..
Thanks in advance...
run() is definitely called if you call start() on fileThread. Check your implementation of run()- its very likely that this method completes or terminates before your check for the print statements. Just an fyi, fileThread.run() is a sequential call while fileThread.start() is a parallel call.
Another vague possibility is that you're not implementing Java's runnable; instead, that may be some custom Runnable class in your project.
EDIT:
So apparently calling fileThread.join() helped you fix your problem, but why does this work? If you call fileThread.join(), the main thread waits until the target (in this case, your fileThread object) terminates.
fileThread.run() never starts a new thread. To start a new thread you have to call fileThread.start().

Categories