I am working on a BTree and I want to synchronize it but the problem is:
I don't want to synchronize the whole method because it has a complex functionality.
My question is: how can I prevent first two or three threads from passing the first condition which root==null?
public void add(TrackingDevice device) {
// Tree is Empty, then add a new elemet to root
if (root == null ) {
root = new BTreeNode(true);
root.keys[0] = device;
root.n++;
} else {
/*
* The root is Full
*/
if (root.n == 2 * t - 1) {
splitRoot();
root.insert(device);
height++;
} else {
root.insert(device);
}
}
}
I would use an AtomicReference with its compareAndSet method.
Then more than one thread may pass the condition root.get() == null and create the root node. But only the fastest thread will write the value via compareAndSet.
I am just suggesting: implement a semaphore-like structure. Define a synchronized counter which your Threads will decrement each time they enter (be careful: this operation must be mutual exclusive) and prevent Threads from entering a section if counter == 0.
You could use an AtomicReference<BTreeNode> for the reference to the root node and use compareAndSet(null, new BTreeNode(true)) to guard entrance to the if block. If the add method is called very frequently this approach ends up creating many short lived BTreeNode instances though. If this is a concern, you can check "manually" first whether the AtomicReference contains null and only if so call compareAndSet.
However, I would get rid of the null check entirely and initially set a root node with n = 0. This makes the code more uniform as then there is no need for checking whether the root exists.
Related
I'm modeling a fastfood drive-through using a priority queue of Event objects (yep, homework). There are three stations, an order, payment and collection station, each with their own queues. I'm having an issue removing an item from the collection station (the last station visited by a Customer). When the collection queue fills up, the simulation begins to loop indefinitely and the timer no longer increments. I assume it's because of this line:
public void processFoodCollection(Customer c, Event e) {
collection.remove(c);//this is the issue I believe
collection.setServerStatus(false);
However, if I attempt to use my standard remove() method (which just calls queue.poll() in the station class), it returns null. I have no idea why this would happen after having just added to the queue, it's given me zero problems any other time I've used it at the other stations (and I just copy-pasted the methods for each station class, they're all identical). I'd really appreciate any help on identifying what is causing this loop, or, if it is the remove(c), how I can fix this.
Here's my Restaurant class (contains the simulation, lazy I know), but hopefully it's not necessary to look at since my documentation isn't complete yet: http://pastebin.com/cHj3xqJN[1]
Here's the method in particular I'm having issue with (collection is a CollectionStation var composed of a queue field, the remove(Customer c) and remove() methods are just for access to the queue methods):
public void processFoodCollection(Customer c, Event e) {
collection.remove(c);//Customer c should be head of queue
collection.setServerStatus(false);//cashier not helping anyone
if (collection.getQueueSize() < 2) {
//process event if room available in collection queue
collection.add(payment.remove());//remove customer from payment queue, add to collection queue
payment.setServerStatus(false);
if (!collection.getServerStatus())
createFinishCollection(collection.peek());//creates event to be processed in the future
//generate new finish payment event for new head of payment queue
if (payment.getQueueSize()>0) {
double b = this.exponentialPay.next();//minutes until finished paying
while (b == 0.0) {
b = this.exponentialPay.next();//ensure return > 0.0
}
createFinishPayment(b, payment.peek());
}
//check if head of order queue can move up
if (order.getQueueSize() > 0) {
if (order.peek().getTimeFinished() == this.clockTime && order.getServerStatus()) {
processFinishOrder(order.peek(), eventList.peek());
} else if (!order.getServerStatus()) {
double timeToOrder = (order.peek().getOrderSize() * this.timeToOrderItem);
createFinishOrder(timeToOrder, order.peek());
}
}
}
}//end method processFoodCollection
If I try to use the remove() method, I get a null pointer exception at:
Event newE = new Event(Events.FINISHFOODCOLLECTION, this.clockTime + (c.getOrderSize() * this.timeToProcessItem), c);
from the null customer object (c). This traces back to the createFinishCollection() method call in the above code. So this is how I know I get a null from calling remove, but I don't understand why my queue would say it's empty when I just added to it. Is there some trick to look out for when indirectly removing data structure elements?
Here's the remove method I'm calling (in the CollectionStation class):
/**
* Removes and returns object at front of queue.
* #return
*/
public Customer remove() {
return customerQueue.poll();
}//end method remove
I'm honestly pretty stumped why this wouldn't work. Any guidance would be appreciated (not looking for answers, just help).
This is how I understand method getUser below :
Return a User object or null
Get a Set of users and assign them to userSer.
If the set is not empty begin iterating over the set but
return the first user within the set.
Here is the method :
private User getUser(UserDet arg)
{
Set<User> userSet = arg.getUsers(User.class);
if (CollectionUtils.isNotEmpty(userSet))
{
for (User user : userSet)
{
return user;
}
}
return null;
}
I think I could replace the method with this :
private User getUser(UserDet arg)
{
Set<User> userSet = arg.getUsers(User.class);
if (CollectionUtils.isNotEmpty(userSet))
{
return userSet.iterator().next();
}
else {
return null;
}
}
This new method removes the loop and just returns the first element in the set, same as original implemention. Is it correct?
Yes. Actually, it's pretty much almost the same thing, as a foreach loop is syntactic sugar for using an iterator from an Iterable.
Note, however, that you don't need the nonempty check in the first variant, since the loop won't iterate in the case of an empty set anyway.
yes both are same. in first implementation, control will return on first iteration of the loop from the function and consequently loop will end.
Yes it is correct, I'd even go for removing the CollectionUtils.isNotEmptySet and use the Iterator's hasNext method... If the set is guaranteed to be non-null.
It seems to be correct, but it will only make the method a bit easier to read, it will not optimize it in terms of performance. Still I think the change is good and you should do it.
Yes, it does pretty much the same, but if your spec says to start iterating then maybe you should - maybe this method will be extended in the future.
BTW: it is a good convention that your method has only one return statement (i.e. you can create a variable, which will be returned, assigned a null at the beginning and assign a user inside your loop)
Yes. Both the methods return the first element in the set. The first method seems to have been written for something else previously and changed then keeping the for loop intact.
In anycase, the second method that you're proposing won't give any significant performance benefit but should be a better way than the first one.
So in case, UserDet#getUsers(Class) never returns null (but an empty Set in case no user could be found), the shortest (and in my opinion most readable) form is:
private User getUser(UserDet arg) {
Set<User> userSet = arg.getUsers(User.class);
return userSet.isEmpty() ? null : userSet.iterator().next();
}
I would do this.
I won't run a loop and more over I'l add a null check.
private User getUser(UserDet arg) {
Set<User> userSet = arg.getUsers(User.class);
if (userSet != null && userSet.size() > 0) {
return userSet.iterator().next();
}
return null;
}
I'm wondering how to accomplish this:
Compare two Stack objects
Do this recursively
After the method that
does this is complete, the Stacks remain as they were to begin with
(i.e. same order, same items).
Only the push, pop and isEmpty methods for Stack is available.
I'm looking more for theoretical help than coding help, but any insight would be appreciated.
Two stacks are identical if their top level elements are identical, and the remaining stacks are identical (namely, the recursive condition).
Now, think what to do just before returning from the method call, in order to leave the stacks the same way they where given at the invocation time.
---EDIT---
The working Java code (derived from Markus A. solution, but with an interesting use of "finally" and with generics):
static <T> boolean compareStacks(Stack<T> a, Stack<T> b) {
if (a.isEmpty() != b.isEmpty()) return false;
if (a.isEmpty() && b.isEmpty()) return true;
T element_a = a.pop();
T element_b = b.pop();
try {
if (((element_a==null) && (element_b!=null)) || (!element_a.equals(element_b)))
return false;
return compareStacks(a, b);
} finally { // restore elements
a.push(element_a);
b.push(element_b);
}
}
In pseudo-code, you could do something like this:
boolean compareStacks(a, b) {
if (a.isEmpty() != b.isEmpty()) return false; // check if one is empty
if (a.isEmpty() && b.isEmpty()) return true; // check if both are empty
element_a = a.pop(); // grab elements and compare them
element_b = b.pop();
if (((element_a==null) && (element_b!=null)) || !element_a.equals(element_b)) {
a.push(element_a); // if they are not equal, restore them and return false
b.push(element_b);
return false;
}
result = compareStacks(a, b); // compare shortened stacks recursively
a.push(element_a); // restore elements
b.push(element_b);
return result; // return result from recursive call
}
With recursion it always helps to think of it as 2 parts, a "Setup" and a recursive function. Your setup would create the proper situation (create the two stacks, pass them in, etc) and then calls the recursive method and when the recursive method is done, report the results.
In your case you probably want this signature for the "recursive" method:
public boolean compareStacks(Stack one, Stack two)
If that method pops & compares the top tow elements of the stack, it can return false right then (saying they don't compare). If they do, you now have two stacks, each one shorter than before. You already know how to compare those two stacks, right (You just wrote the method to do so!).
at the end you can "Push" your one element back onto each stack to restore it's previous state before returning.
There will be a little trickiness in restoring the stack in the case where they don't compare, and ensuring that if the compareStack you call fails it properly passes that up to the previous state, even if the "current" compareStack succeeds, but those are implementation details--just thought I'd mention those so you don't overlook them.
There is a cute solution with Try/finally (no catch, return from within the try and push back onto the stack in the finally) that would make the code pretty slick, but it's easy enough without it.
I'm working on a project for school but i'm a little stuck right now
My problem is that i have an arrayList of Squares
Each Square has a value(from 0 to 100). Its starting value is 9999 so i can check if its is checked.
If a square is checked i want it to be removed from the arrayList.
So after a while there will be no Squares left.
there is a little bit of code where the first value is set so thats why i check if the value is 9999.
But i get an error. One that i havent seen before.
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
Vak = Square
this is my code:
while (!vakken.isEmpty()) { // check if empty
Iterator itrVak = vakken.iterator();
while (itrVak.hasNext()) {
Vak vak = (Vak) itrVak.next(); // here is get the error
if (vak.getValue() != 9999) {// check if square value is 9999
Collection checkVakken = vak.getNeighbour().values();
Iterator itre = checkVakken.iterator();
while (itre.hasNext()) {
Vak nextVak = (Vak) itre.next();
if (nextVak != null) {
if (nextVak.getValue() == 9999) {
nextVak.setValue(vak.getValue() + 1); // set value by its neighbour
vakken.remove(vak);
checkvakken.add(vak);
}
}
}
} else {
vakken.remove(vak);
checkvakken.add(vak);
}
}
}
You are removing elements from the collection while you are iterating it. As the iterator may produce unpredictable results in this situation, it fails fast throwing the exception you encountered.
You may only alter a collection through the iterator's methods while traversing it. There should be remove method on the iterator itself, that removes the current element and keeps the iterator intact.
While iterating, you should use Iterator instance for removing object:
itre.remove();
You can try like this:
itre.remove();
ITERATOR never lets you modify when you are iterating.. you need to use loops instead.. this happens coz you are using the Iterator, same time other thread is modifying the list...
Recursion is a new practice for me and I am trying to get better at it and understand how the methods return. I have the following program but am unfailiar with how to use the this keyword. Can you please review the code and walk me through the program showing the values held by the variables as the methods execute?
I have tried numerous things to determine how the value answer in the compute method holds 14 after execution can anyone walk me through the first few recursive calls so I can try and figure out the rest?
public class Recurs1 {
public static void main (String [] arg) {
Recurs1 r = new Recurs1();
r.compute();
}
public void compute() {
int [] stuff = {1, 2, 3, 4};
int answer = this.go(stuff, 0);
System.out.println("The answer is " + answer);
}
private int go(int[] numbers, int spot) {
if (numbers.length == spot) return spot;
int value = this.go(numbers, spot + 1 );
return value + numbers[spot];
}
}
Ok so a few things I notice here:
The purpose of go() seems to be calculating the sum of the numbers in the array. If this is the case, your method should look like this:
private int go(int[] numbers, int spot) {
if (numbers.length - 1 == spot) return numbers[spot];
int value = this.go(numbers, spot + 1 );
return value + numbers[spot];
}
This is because numbers.length in this case will return 4, but the last element in this array is at index 3 (arrays are 0-indexed).
This way, when the function is called with the second parameter set to 3, it will return the value of the last element in the array and then the code will "bubble up" (as I like to call it) and calculate the sum of the elements by subsequently returning the current summed value + the value of the current call.
As for your problem with the this keyword, it's actually very simple. this always refers to the current class instance your code is in. In this case, you create a Recurs1 instance called r in your main function so whenever you call a method on that particular object, the this keyword used in those methods will refer to r. If you created multiple Recurs1 objects (each with potential different internal states) in your program, their respective this references would always point to themselves allowing you to access their member variables and methods.
Hope that helps and good luck, recursion is usually what most people have trouble getting their heads around at first but once you get used to it it's pretty cool!
OK so this is not an answer to your question per se, more like a lesson in recursion.
Keep in mind I have never tried to to do this with a java class.
Recursion means a function that calls itself repeatedly until a answer has been reached, or your function detects you are running out of stack space.
You first step into the function determines if you will call yourself.
When you call yourself you will push a new copy of the data onto the stack and begin executing. I think in the case of java you will allocate a new object into the heap ( don't quote me on this ) and each invocation will have a new set of variables that get populated with new values.
As you recurse deeper and deeper you simply allocate new copies of the object until you find the answer or run out of memory.
If you find the answer you then return the result to the previous level in the stack of objects eg:
int foo(int i ){
if(some condition){
return foo(i);
} else
return i
}
as You can see if the condition tests true the foo() keeps getting called. Now at each call, the variables of foo() are saved for as many levels deep as you go. If the condition tests false then each instance of foo() returns to the previous until you are at the original invocation of foo() which then returns to the caller of foo().
Clear as Mud?