How to add multipl object in blocking queue? - java

BlockingQueue<ServiceSync>bq=new LinkedBlockingDeque<ServiceSync>();
ServiceSync s=new ServiceSync();
s.setService(OperationsConst.CODE, commonUtil.DOWNLOAD, true,null );
bq.add(s);
//s=new ServiceSync();
s.setService(OperationsConst.LOGIN, commonUtil.DOWNLOAD, true,null );
bq.add(s);
tmp=new TempThread(bq, context);
tmp.setBlockingQueue(bq);
Here, I added 2 objects but every time, only the second object is added in the queue.

You have used the same reference s after changing the value. Please create another object of ServiceSync, set the value you want and add to queue as show below.
BlockingQueue<ServiceSync> bq = new LinkedBlockingDeque<ServiceSync>();
ServiceSync s1 = new ServiceSync();
s1.setService(OperationsConst.CODE, commonUtil.DOWNLOAD, true, null);
bq.add(s1);
ServiceSync s2 = new ServiceSync();
s2.setService(OperationsConst.LOGIN, commonUtil.DOWNLOAD, true, null);
bq.add(s2);

Currently you are adding s to the queue, change the value you added and add it second time. So you end up with a queue that has the same object there twice. Either uncomment the s=new ServiceSync(), or (better) create a new variable of type ServiceSync and add it to the queue.

Related

How to pass the entire list of id in params?

I am getting a response in this list retailers object.
List<Retailers> retailers;
Say for eg: retailers.getId() returns 1,2,3,4,5,6,7,8 in response and this works fine.
Now I need to store this in another List and pass it in params. But only first value 1 is getting stored in all case.
Below is my code for this
List<RoutePlanDayRequests> routePlanDayRequests = new ArrayList<RoutePlanDayRequests>();
RoutePlanDayRequests requests = new RoutePlanDayRequests();
for(int i= 0; i<retailers.size();i++){ //retailers is already having datas.
Log.e("retailers",retailers.get(i).getId()); //here i am getting 1,2,3,4,5
requests.setPartnerId(retailers.get(i).getId());
routePlanDayRequests.add(requests); //but while storing i get only 1.
updateServiceList(AppUtils.getMsisdn(mSharedPreferences), routePlanDayRequests);
}
Output Response:
[{"Id":"1"},{"Id":"1"},{"Id:"1"},{"Id":"1},{"Id":"1"},{"Id":"1"},{"Id":"1"}]
Instead it should get all elements (1,2,3,4,5 from retailers.getId) and pass it in params.
Anybody has any idea why this is happening?
You must create RoutePlanDayRequests in the loop and send all collected data at the end (outside of the loop) to the updateService
List<RoutePlanDayRequests> routePlanDayRequests = new ArrayList<RoutePlanDayRequests>();
// you can use the simpler syntax of the for-loop
for(Retailer retailer : retailers) {
// create the requests object in the loop
RoutePlanDayRequests requests = new RoutePlanDayRequests();
Log.e("retailers",retailer.getId());
requests.setPartnerId(retailers.get(i).getId());
routePlanDayRequests.add(requests);
}
// call the service outside of the loop
updateServiceList(AppUtils.getMsisdn(mSharedPreferences), routePlanDayRequests);
}

Retreving only latest record in iteration after adding multiple values to list using java

I'm trying to add multiple records to a list and iterate. But its displaying only latest records added
Here is my code
List<ExportBean> exportBeans = new ArrayList<ExportBean>();
ExportBean exportBean = new ExportBean();
exportBean.setBooleanValue(true);
exportBean.setKeyValue("PRE_APPROVED_OFFER");
exportBean.setStringValue("111");
exportBeans.add(exportBean);
exportBean.setBooleanValue(true);
exportBean.setKeyValue("PRE_APPROVED_OFFER1");
exportBean.setStringValue("222");
exportBeans.add(exportBean);
getLopRefNo(exportBeans);
when I iterate it
def getLopRefNo = {
exportBeans->
println "in function ${exportBeans}"
}
It shows only
in function [ExportMessagingBean{stringValue='222', keyValue='PRE_APPROVED_OFFER1', exportBoolean=true}, ExportMessagingBean{stringValue='222', keyValue='PRE_APPROVED_OFFER1', exportBoolean=true}]
It doesnt show the first record added. Is it missing anything?
The problem has nothing to do with Groovy. In your code, you are not actually adding two objects, you are adding one object and modifying it.
List<ExportBean> exportBeans = new ArrayList<ExportBean>();
ExportBean exportBean = new ExportBean();
exportBean.setBooleanValue(true);
exportBean.setKeyValue("PRE_APPROVED_OFFER");
exportBean.setStringValue("111");
exportBeans.add(exportBean); // add object to list
exportBean.setBooleanValue(true);
exportBean.setKeyValue("PRE_APPROVED_OFFER1");
exportBean.setStringValue("222");
exportBeans.add(exportBean); // this time, the same reference is "added". This does not result in an addition (in fact, "add" will return false here
getLopRefNo(exportBeans);
You are calling add with an object that is already present in the list so it has no effect. What you should do is create another instance of ExportBean, like this:
List<ExportBean> exportBeans = new ArrayList<ExportBean>();
ExportBean exportBean = new ExportBean();
exportBean.setBooleanValue(true);
exportBean.setKeyValue("PRE_APPROVED_OFFER");
exportBean.setStringValue("111");
exportBeans.add(exportBean); // add object to list
exportBean = new ExportBean(); //create new instance of ExportBean
exportBean.setBooleanValue(true);
exportBean.setKeyValue("PRE_APPROVED_OFFER1");
exportBean.setStringValue("222");
exportBeans.add(exportBean); // this new instance will be correctly added
getLopRefNo(exportBeans);
You only have one ExportBean object in your code (you only said new ExportBean() once) so you have added the same object to the list twice. Your second set of calls to the set methods on the bean just updates your existing object rather than creating a new one.

Berkeley JE StoredMap : replace existing value without loading previous one

I want to update a StoredMap value and I don't care about the old value. I cannot find a way to avoid the previous value from being loaded.
StoredMap<Integer, SyntaxDocument> tsCol = new StoredMap<Integer, SyntaxDocument>(tsdb, new IntegerBinding(), new PassageBinding(), true);
tsCol.put(1, doc); // insert value => ok
tsCol.put(1, doc); // <- load previous value but I don't care. I want to avoid the "heavy" PassageBinding process.
tsCol.putAll(Collections.singletonMap(1, doc)); // Even this one load the old value
Is there a way to optimize my code and update an existing value without loading it (or at least to prevent the binding to process old DatabaseEntry bytes)?
NOTE: that calling remove then put is slower.
Solution is to use lowlevel Database API :
Database tsdb = environment.openDatabase(null, "tsdb", dbconfig);
PassageBinding binding = new PassageBinding();
DatabaseEntry idDbEntry = new DatabaseEntry();
IntegerBinding.intToEntry(id, idDbEntry);
DatabaseEntry dbEntry = new DatabaseEntry();
pb.objectToEntry(data, dbEntry);
tsdb.put(null, idDbEntry, dbEntry); // <-- replace existing value without loading it.

How to get the updated list in main method

I am having a list of queues as follows:
public class QueueSelection {
public List initQueueCollection()
{
QueueLoad d1 = new QueueLoad("QUEUEA1", "QUEUEB1", true);
QueueLoad d2 = new QueueLoad("QUEUEA2", "QUEUEB2", false);
QueueLoad d3 = new QueueLoad("QUEUEA3", "QUEUEB3", true);
QueueLoad d4 = new QueueLoad("QUEUEA4", "QUEUEB4", false);
List list = new ArrayList();
list.add(d1);
list.add(d2);
list.add(d3);
list.add(d4);
return list;
}
Now from the main method, i call the above method like,
QueueSelection selection = new QueueSelection();
List<QueueLoad> queueList =selection.initQueueCollection();
When the first input/file comes, queue is checked to see which one of these is false, so I am fetching the second one ("QUEUEA2", "QUEUEB2", false);
As soon as I fetch it, I should change the status to true like ("QUEUEA2", "QUEUEB2", true); I am doing it using
for (QueueLoad s:queueList)
{
if(s.getStatus()==false)
{
str1=s.getQueueName1();
str2=s.getQueueName2();
str3=s.getStatus();
particularCollection=s;
System.out.println(s);
particularCollection.setStatus(true);
particularCollection.setQueueName1(str1);
particularCollection.setQueueName2(str2);
int j=queueList.indexOf(particularCollection);
System.out.println("The index is"+j);
s = new QueueLoad(str1, str2, true);
newqueueList=queueList.set(j, s);
And the list is updated. Now when the second input comes, since in the first line it is seeing the List<QueueLoad> queueList =selection.initQueueCollection();
it is always getting the old list and not the updated one.
Please help.
Now when the second input comes, since in the first line it is seeing
the List queueList =selection.initQueueCollection(); it is
always getting the old list and not the updated one.
I interpret this to mean that you don't want the init method to be invoked again 'when the second input comes'.
There are a lot of ways to address this. Have you considered moving the init method into the constructor for QueueSelection, for example?
Take a look at the javadocs for ArrayList.set. It returns the old value at that location. So you'll want to do:
queueList.set(j, s);
newqueueList = queuelist;
If I have understood you correctly then you're problem is that at each new input you are intializing a new list. Maybe just put queueList as class attribute?
Also:
newqueueList=queueList.set(j, s);
I think set() returns the object that was previously at that index. So your newqueueList would actually contain a QueueLoad object.
Since you haven't shown your main() method, I'm not certain what it looks like, but something along these lines should work:
Instead of:
QueueSelection selection = new QueueSelection();
List<QueueLoad> queueList =selection.initQueueCollection();
Declare queueList outside the method something like this:
private static List<QueueLoad> queueList = null;
Then, in the method,
if (queueList == null)
{
QueueSelection selection = new QueueSelection();
queueList =selection.initQueueCollection();
}

different of defining object inside and outside loops in Java

I was struggling with part of my code today to read some data from a file and add them to an object as its properties (I'm aware of how to add/read object in file without this hassle but wanted to do it this way) as below:
file is like this:
111,john,23.1
222,jack,22.5
234,adam,12.8
I was trying to read this file using following:
public ArrayList<Staff> LoadAllStaffs(){
ArrayList<Staff> staffs = new ArrayList<Staff>();
File file = new File(stafffile);
Staff tmpstaff = new Staff();
try {
BufferedReader inputfile = new BufferedReader(new FileReader(stafffile));
String tmp;
while((tmp = inputfile.readLine()) != null){
StringTokenizer st = new StringTokenizer(tmp , ",");
tmpstaff.setID(Integer.valueOf(st.nextToken()));
tmpstaff.setFirstName(st.nextToken());
tmpstaff.setSalary(Double.valueOf(st.nextToken()));
staffs.add(tmpstaff);
}
}
catch (IOException e) {
}
return staffs;
}
using println this output shown from the returned ArrayList:
234,adam,12.8
234,adam,12.8
234,adam,12.8
I just moved the Staff tmpstaff = new Staff(); inside the while loop and it shows what it should.
why this is happening? I read -even here- that defining variables (well, here its an Object ) inside or outside loops doesn't make any difference.
You are not creating a new Staff instance inside the loop, you are reusing the same instance for all the iterations. So, you overwrite the values and add the same object.
Move
Staff tmpstaff = new Staff();
to the first line inside the loop.
UPDATE: To address Vash's comment, the issue here is that can be explained as that, if you want to store 3 objects, you need to create such 3 objects. You can reuse the reference (the tmpstaff variable) and effectively where it is defined it is not important (as long as all references to it are in the same scope. But you must create the 3 objects, which means 3 new commands.
UPDATE 2: To put things simpler, the text I read -even here- that defining variables (well, here its an Object ) inside or outside loops doesn't make any difference. means that
File file = new File(stafffile);
Staff tmpstaff = null; // or simpler, Staff tmpstaff;
try {
...
while((tmp = inputfile.readLine()) != null){
tmpstaff = new Staff();
...
and
while((tmp = inputfile.readLine()) != null){
Staff tmpstaff = new Staff();
...
are equivalent.
The operator new is responsible for "object creation" called instance. So when you create him outside the loop you have only one instance, that you modify every loop run. When you create that object inside the loop you have separate instance for each run.
Well Java operates by reference on Objects. Because you are creating only one Staff() Object, there's only one Reference. Therefore, in the while Loop you change just the attributes of the Object and add the same Reference three times to the List.
You can define the variables outside the loop, but you have to instantiate a new Object inside the loop so it lookes like this:
Staff tmpStaff
while((tmp = inputfile.readLine()) != null){
tmpStaff = new Staff();
[additional Code here]
}
If you want to create a new Staff on each pass of the loop, then you have to do the creation inside of the loop before using it.
Done outside the loop as you did, you created a new Staff indeed, but that same keeps being used each time.
A new object is created only when the new keyword is used.

Categories

Resources