I wrote a method which behaves as a round robin. Everytime someone calls it, it returns an integer from a list. When the end of the list is reached, it starts serving from the beginning.
I call this method from a stateless session bean.
The method is written in a util class like below
public final class MyUtil {
private static int index;
private MyUtil() {}
public synchronized static int getNextInt() {
Properties p = DBconfigModule.getProperties("key");
List<String> list = Arrays.asList(((String) p.get("key")).split(","));
try {
if(index>=list.size()) {
index = 0;
next = list.get(0);
index++;
} else {
next = list.get(index):
index++;
}
} catch(final Exception e) {
// log
index = 0;
next = list.get(0);
index++;
}
return Integer.parseInt(next);
}
#Stateless
public class Usage {
public int getNextInt() {
return MyUtil.getNextInt();
}
}
I am not sure how far what i have written is right and will work.
Can anyone tell me is this right and suggest me if it can be improved?
I do not want to use any 3pp libraries for this.
Thank you.
Your code is correct only if list is never changed or if access to list is synchronized with the same monitor.
Imagine what happens when the following code is executed:
Thread 1 Thread 2
------------------- -----------------------
// index = 2
// list.size() = 3
if (index == list.size()) {
// Removes first element
// now list.size() = 2
list.remove(0);
} else {
// Will throw an exception
// Because now list has size 2
// and the third element (index 2)
// doesn't exists
next = list.get(index);
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Counter {
private ReadWriteLock listLock = new ReentrantReadWriteLock();
private List<Integer> list = new ArrayList<>();
private AtomicInteger indexCounter = new AtomicInteger(0);
Integer getNextInt() {
Lock readLock = listLock.readLock();
try {
if(list==null || list.size() == 0) {
throw new IllegalStateException("Call setList() with some values first.");
}
int index = indexCounter.incrementAndGet() % list.size();
return list.get(index);
} finally {
readLock.unlock();
}
}
void setList(List<Integer> newList) {
Lock writeLock = listLock.writeLock();
try {
this.list = newList;
} finally {
writeLock.unlock();
}
}
}
Something like that, very roughly.
Related
I'm creating methods that will be used for buttons one that will return the next Photo object in my array and when it gets to the end will start over moving through the list. The other that will get the previous Photo Object and will start at the end when it reaches the beginning
My issue is that the loop always returns true and if I use listIterator.next I get an error, my class also implements collection if that helps any
public Photo next() {
ListIterator<Photo> listIterator = PhotoAlbum.photo.listIterator();
if (this.size() == 0) {
return null;
}
if (listIterator.hasNext()) {
Photo output = listIterator.next();
return output;
}
return PhotoAlbum.photo.get(0);
}
public Photo previous() {
ListIterator<Photo> listIterator = PhotoAlbum.photo.listIterator();
if (this.size() == 0) {
return null;
}
if (listIterator.hasPrevious()) {
return listIterator.previous();
}
return PhotoAlbum.photo.get(this.size()-1);
}
You should store the current index of the photo inside a variable.
private int currentPhotoIndex = 0;
Then your functions will increment/decrement it depending on the operation
private int currentPhotoIndex = 0;
public Photo next() {
if (this.size() == 0) {
return null;
}
if (this.currentPhotoIndex < this.size()) {
this.currentPhotoIndex++;
} else {
this.currentPhotoIndex = 0;
}
//I think here it should be: return this.get(currentPhotoIndex), but I sticked to your code
return PhotoAlbum.photo.get(currentPhotoIndex);
}
public Photo previous() {
if (this.size() == 0) {
return null;
}
if (this.currentPhotoIndex > 0) {
this.currentPhotoIndex--;
} else {
this.currentPhotoIndex = this.size() - 1;
}
//I think here it should be: return this.get(currentPhotoIndex), but I sticked to your code
return PhotoAlbum.photo.get(currentPhotoIndex);
}
You can do it simple using ListIterator, here is an example of that.
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Thomas");
names.add("Andrew");
names.add("Ivan");
ListIterator li = names.listIterator();
while(li.hasNext()) {
System.out.println(li.next());
}
while(li.hasPrevious()) {
System.out.println(li.previous());
}
}
}
Of course that is only a simple example, but you can adapt it to your needs.
import java.util.ArrayList;
import java.util.List;
public class QueryParser {
QueryParameter queryParameter = new QueryParameter();
public static int flag = 0;
public QueryParameter parseQuery(String queryString) {
queryParameter.setGroupByFields(getGroupByFields(queryString));
queryParameter.setAggregateFunctions(getAggregateFunctions(queryString));
return queryParameter;
}
private List<AggregateFunction> getAggregateFunctions(String queryString) {
List<AggregateFunction> aggregateFunctionList = null;
AggregateFunction aggregateFunction;
if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
|| queryString.contains("max") || queryString.contains("avg")) {
flag = flag + 1;
}
return aggregateFunctionList;
}
private List<String> getGroupByFields(String queryString) {
List<String> groupByFieldList = null;
if (queryString.contains("group by")) {
flag = flag+2;
return groupByFieldList;
}
}
this is my code, now i am accessing flag from another class using
int i = queryParser.flag,
but it always returns 0. How to declare flag so that it will hold the values from the inner methods and also can be accessed from other classes. /* if anyone need more details please ask i'll add more details, and what more should i write,my main doubt is only to know how i can utilise my flag in another class, thank you for being patient*/
An MCVE could look like this:
public class QueryParser {
public static int flag = 0;
void getAggregateFunctions(String queryString) {
if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
|| queryString.contains("max") || queryString.contains("avg")) {
flag = flag + 1;
}
}
void getGroupByFields(String queryString) {
if (queryString.contains("group by")) {
flag = flag+2;
}
}
public static void main(String[] args) {
QueryParser q = new QueryParser();
System.out.println(flag); //prints out 0
q.getAggregateFunctions("max"); System.out.println(flag); //prints out 1
q.getAggregateFunctions("aString"); System.out.println(flag); //prints out 1
q.getAggregateFunctions("avgNumber"); System.out.println(flag); //prints out 2
q.getGroupByFields("group by"); System.out.println(flag); //prints out 4
}
}
It helps those who want to help you, and far more important: it is a great debugging tool.
Making on helps you isolate the problem, and focus on it.
Like in this case: you can see that the problem is not in the declaration of flag, nor changing its value, but maybe with the input values.
.. and by repeated, I mean repeated. I have a simple implementation of a list interface, functioning like a simple baby-version of the LinkedList.
I have the classes "Knoten"(means "knot" in German), MyLinkedList and, well, Main.
The Error my compiler tosses at me originates in class Knoten, line 35.
But it doesn´t tell me what kind of error it is.
"at Knoten.nextN(Knoten.java:35)"
is all it says. A million times. My whole cmd window is filled with this line. I bet it printed this error message for more than hundred times, again and again. I tried to search for similar problems, but couldn´t really find anything useful because I don´t know which error to search for.
Why did my program crash?
Please help..
Knoten:
class Knoten<T> {
Knoten nachfolger;
T t;
public Knoten(T t){
this.t = t;
nachfolger = null;
}
public void add(T tneu) {
if (nachfolger != null) {
nachfolger.add(tneu);
}
else {
Knoten kneu = new Knoten(tneu);
nachfolger = kneu;
}
}
public Knoten giveNachfolger(){
return nachfolger;
}
public T fuerIDGeben(int index, Knoten anfang) {
if(index == nextN(anfang)){
return (T) nachfolger.t;
}
return null;
}
private int nextN(Knoten k){
int i = 1;
if (nachfolger != null){
i = i+1;
nextN(nachfolger);
} else {}
return i;
} }
MyLinkedList:
class MyLinkedList<T> implements MyList<T>{
Knoten anfang;
public MyLinkedList<T>(){
anfang = null;
}
public T get(int index){
return (T) anfang.fuerIDGeben(index, anfang);
}
public void add(T t){
if(anfang != null){
anfang.add(t);
} else {
Knoten newKnoten = new Knoten(t);
anfang = newKnoten;
}
}
public MyIterator<T> iterate(){
return new MyLinkedIterator<T>();
}
private class MyLinkedIterator<T> implements MyIterator<T>{
public boolean hasNext(){
if(anfang.giveNachfolger() != null){
return true;
}
return false;
}
public T next(){
if(anfang.giveNachfolger() != null){
return (T) anfang.giveNachfolger().t;
}
return null;
}}}
import java.util.*;
And Main:
class Main{
public static void main(String[] args){
MyList<Integer> list = new MyLinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
System.out.println(list.get(0));
MyIterator<Integer> it = list.iterate();
while(it.hasNext()){
System.out.println(it.next());
}
}}
You have infinite recursion in nextN(), leading to a stack overflow.
If you look closely at the implementation of nextN(), it repeatedly calls itself with the same argument. This continues until the JVM runs out of stack, at which point you get a StackOverflowError. The stack trace at the point of the exception will mention nextN() many times.
Since you are not using k in the nextN function, it always calls itself with the same parameter and brings infinite loops.
Instead of that, you should call the nextN function with the member variable of k in order to iterate over them.
If you have a link like:
k -> k.nachfolger -> k.nachfolger.nachfolger -> ...
Then you need to change your function with this:
private int nextN(Knoten k){
if (k.nachfolger != null){
return nextN(k.nachfolger) + 1;
}
return 1;
}
I have made a Priority Queue class with an array list, but I am having trouble with the insert and delMin (delete minimum areas). I cannot create more functions and here is my code:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyMinPQ<E extends Comparable<E>> implements Iterable<E> {
private ArrayList<E> pq;
private int N;
public MyMinPQ() {
pq = new ArrayList<E>();
}
public E delMin(){
E minVal = min();
pq.remove(0);
N--;
return minVal;
}
public E min (){
if (isEmpty())
throw new NoSuchElementException();
return pq.get(0);
}
public void insert (E item){
for (int i = 0; i < N; i++){
pq.add(item);
if (pq.get(i) > pq.get(i+1)) {
E tmp = pq.get(i);
pq.set(i+1, tmp);
}
}
N++;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public Iterator<E> iterator() {
return new Iterator<E>(){
int current = 0;
public boolean hasNext() {
return current != size();
}
public E next() {
if (hasNext())
return pq.get(current++);
else throw new NoSuchElementException( );
}
public void remove() {
throw new UnsupportedOperationException( );
}
};
}
}
At the insert portion of the code, I know that I have to sort the new additions to Arraylist but I am having issues with going about this. I tried to compare the values that is within the list, but eclipse does not allow it based on how I formatted it. When I use compareTo, it does not work with my iterator and everything goes into disarray.
My question is how can I go about modifying my insert function so it can sort new items in descending order? Will my delMin() also have to change because of it?
try this
public void insert(E item) {
int i = 0;
while (i < N && pq.get(i).compareTo(item) <= 0) {
i++;
}
N++;
}
I am posting this as an question since I want to clarify with you guys on the concept of using F/J framework in Java 1.7 as I see some of the example on the internet does not seem to make sense.
The Code using a List instead of array is intentional.
Here is the linear/regular version of recursive merge sort.
package org.algorithms.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MergeSortor<T> {
private final List<T> items;
private final Comparator<T> c;
public MergeSortor(final List<T> original, final Comparator<T> c) {
if (original == null) {
this.items = Collections.emptyList();
} else {
this.items = original;
}
this.c = c;
}
protected List<T> compute() {
List<T> result = null;
int currentSize = this.items.size();
if (currentSize <= 1) {
result = items;
} else{
int midPoint = currentSize / 2;
List<T> left =new MergeSortor<T>(items.subList(0, midPoint), c).getSortedResult();
List<T> right =new MergeSortor<T>(items.subList(midPoint,
currentSize), c).getSortedResult();
result = merge(left,right);
}
return result;
}
private List<T> merge(List<T>left,List<T>right) {
List<T> result = new ArrayList<T>(left.size()+right.size());
T firstLeft = null;
T firstRight = null;
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
firstLeft = left.get(0);
firstRight = right.get(0);
if (c.compare(firstLeft, firstRight) <= 0) {
result.add(firstLeft);
left = left.subList(1, left.size());
} else {
result.add(firstRight);
right = right.subList(1, right.size());
}
} else if (left.size() > 0){
result.add(left.get(0));
left = left.subList(1, left.size());
} else if (right.size() > 0){
result.add(right.get(0));
right = right.subList(1, right.size());
}
}
return result;
}
public List<T> getSortedResult() {
return this.compute();
}
static public class IntegerComparator implements Comparator<Integer> {
#Override
public int compare(Integer o1, Integer o2) {
int f = o1.hashCode(); // Auto-unboxing
int s = o2.hashCode(); // Auto-unboxing
return f < s ? -1 : (f == s ? 0 : 1); // No unboxing
}
}
}
And here is the F/J version of the merge sort extending The RecursiveTask.
package org.algorithms.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.RecursiveTask;
public class MergeTask<T> extends RecursiveTask<List<T>>{
private final List<T> items;
private final Comparator<T> c;
private static final long serialVersionUID = 8193108777395886772L;
public MergeTask(final List<T> original, final Comparator<T> c){
if (original == null) {
this.items = Collections.emptyList();
} else {
this.items = original;
}
this.c = c;
}
#Override
protected List<T> compute() {
List<T> result = null;
int currentSize = this.items.size();
if (currentSize <= 1) {
result = items;
} else{
int midPoint = currentSize / 2;
MergeTask<T> leftSortor = new MergeTask<T>(items.subList(0, midPoint), c);
MergeTask<T> rightSortor = new MergeTask<T>(items.subList(midPoint,
currentSize), c);
rightSortor.fork();
leftSortor.fork();
result = merge(leftSortor.join(),rightSortor.join());
}
return result;
}
private List<T> merge(List<T>left,List<T>right) {
List<T> result = new ArrayList<T>(left.size()+right.size());
T firstLeft = null;
T firstRight = null;
while (left.size() > 0 || right.size() > 0) {
if (left.size() > 0 && right.size() > 0) {
firstLeft = left.get(0);
firstRight = right.get(0);
if (c.compare(firstLeft, firstRight) <= 0) {
result.add(firstLeft);
left = left.subList(1, left.size());
} else {
result.add(firstRight);
right = right.subList(1, right.size());
}
} else if (left.size() > 0){
result.add(left.get(0));
left = left.subList(1, left.size());
} else if (right.size() > 0){
result.add(right.get(0));
right = right.subList(1, right.size());
}
}
return result;
}
}
and here is the main program that calls them.
package org.algorithms.sort;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import org.algorithms.sort.MergeSortor.IntegerComparator;
public class SortingRunner {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Integer[] initialOrders = new Integer[Short.MAX_VALUE*32];
Random random = new Random();
for (int i =0 ;i<Short.MAX_VALUE*32;i++){
initialOrders[i]=Integer.valueOf(random.nextInt(Integer.MAX_VALUE));
}
MergeSortor<Integer> sortor = new MergeSortor<Integer>(
Arrays.asList(initialOrders), new IntegerComparator());
ForkJoinPool pool = new ForkJoinPool();
MergeTask<Integer> task = new MergeTask<Integer>(Arrays.asList(initialOrders), new IntegerComparator());
long start = System.currentTimeMillis();
sortor.getSortedResult();
long end = System.currentTimeMillis();
System.out.println(end - start );
start = System.currentTimeMillis();
pool.invoke(task);
end = System.currentTimeMillis();
System.out.println(end - start );
}
}
What I considered the problem on the internet is that the forking in most of the example is to fork both legs together of the dividing task or fork the left dividing part first then fork the right.
In the case of using F/J on merge sort, I think it should be a big no no.
Merge sort is actually linear dependent sorting from left to right. Forking left first does not generate any further parallel process that it is already there. F/J framework is putting everything your fork() in sequence of submission in a queue, then picked up and execute in the order of submission, separately by each worker thread of the F/J pool.
However, forking right first will give you the advantage of parallel computing of what should be execute later(comparing with the original/linear implementation) ahead of time and do the divide/merge of the tail first.
Let me know what you guys think. and hope this will be a good example for using F/J with sorting.