I heard the same rule that applies for variables doesn't apply when we're talking about data structures. Is this true?
For instance, this, which is perfectly fine
public class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
does not mean that the following will work flawlessly.
public class SynchronizedDataStructures {
private ArrayList<String> c = new ArrayList<String>();
public synchronized void add1(element) {
c.add(element);
}
public synchronized void clear1() {
c.clear();
}
public synchronized int value() {
return c;
}
}
Is this true and what can I do to make it work for data structures?
If you change add1(element) to add1(String element), and remove the value() method, this will compile, and be thread safe.
You will need a method which correctly accessing the contents of the list. e.g.
public synchronized int value(int index) {
return c.get(index);
}
There is a more clean way to synchronize on an object and not on a complete method. Consider this:
...
public void clear1() {
synchronized(c) {
c.clear();
}
}
...
http://tutorials.jenkov.com/java-concurrency/synchronized.html
This is a nice explanation of synchronized in Java.
Related
If I have a singleton class like:
public class MySingleton(){
private static MySingleton istance;
private int element;
private MySingleton(){element = 10;}
public static MySingleton getIstance() {
if(istance == null)
istance = new Mysingleton();
return istance;
}
public void setElement(int i ){
element = i;
}
public int getElement(){
return element;
}
}
and I want to change element's value by calling
MySingleton.getIstance().setElement(20)
Will it change the element value for the istance? Here's an example:
... main () {
MySingleton.getIstance().setElement(20);
System.out.prinln(MySingleton.getIstance().getElement());
// It displays 10, why ?
I suggest you use an enum as it is simpler and thread safe (but not your getter/setter)
public enum MySingleton() {
INSTANCE;
private int element = 10;
public void setElement(int element) { this.element = element; }
public int getElement() { return element; }
}
MySingleton.INSTANCE.setElement(20);
System.out.prinln(MySingleton.INSTANCE.getElement()); // prints 20.
I'm not sure if your code block above was copied in or just retyped, but there were a few basic compilation issues I saw with it - when you're setting MySingleton in getInstance, you need to check capitalization. Also, your class declaration shouldn't have (parentheses). After fixing these two things and running basic main, I got 20.
This is the same as what you had - no synchronization or anything else, but on a single thread it doesn't seem necessary.
public class MySingleton{
private static MySingleton istance;
private int element;
private MySingleton(){element = 10;}
public static MySingleton getIstance() {
if(istance == null)
istance = new MySingleton();
return istance;
}
public void setElement(int i ){
element = i;
}
public int getElement(){
return element;
}
public static void main(String[] args) {
System.out.println(MySingleton.getIstance().getElement());
MySingleton.getIstance().setElement(20);
System.out.println(MySingleton.getIstance().getElement());
}
}
should have an output of
10
20
Im not sure if your code really work, how azurefrog say, make your code synchronized, and in youre line public static getIstance() { you need to set the return type.
I have a public integer variable (MainReg) in my Counter Class. I want to get value of this variable and set it in my JComponent class. Here is piece of my JComponent class:
public class Komponent2 extends JComponent implements ActionListener
{
Counter counter3;
.
.
.
int a = counter3.valueOf(MainReg);
But it doesn't work. I tried also:
int a = valueOf(counter3.MainReg);
int a = counter3.valueOf(counter3.MainReg);
int a = counter3.MainReg;
But it still doesn't work. How can I get this variable? Thanks for helping me.
EDIT
Here is my Counter class:
import java.util.Observable ;
public class Counter extends Observable
{
public int MainReg;
public int CompareReg;
public Mode countMode;
public boolean OVF;
private int a=0;
public Counter()
{
OVF=false;
}
public void setCompareReg(int dana)
{
CompareReg=dana;
}
public void setMainReg(int dana2)
{
MainReg=dana2;
}
public void setMode(Mode countMode)
{
this.countMode=countMode;
}
public void Count()
{
if (countMode==Mode.UP)
{
MainReg++;
OVF=false;
if (CompareReg < MainReg)
{
OVF=true;
MainReg=0;
setChanged();
notifyObservers();
}
}
else if (countMode==Mode.UPDOWN)
{
if(MainReg >= CompareReg)
{
a=MainReg;
MainReg--;
OVF=true;
}
else
{
if(MainReg >= a)
{
MainReg++;
OVF=false;
}
else
{
MainReg--;
if(MainReg==0)
{
a=0;
}
OVF=false;
}
}
}
else if (countMode==Mode.CONTINOUS)
{
MainReg++;
OVF=false;
if (65536 < MainReg)
{
MainReg=0;
OVF=true;
}
}
}
}
Well I see two ways you can do this.
Your MainReg integer is public, you could simply use int i = counter3.MainReg;
Or you could create a getMainReg() method in your Counter class. Then call it from whatever class.
EX:
public int getMainReg() {
return this.MainReg;
}
Give your Counter class getter methods, and then call them when you need to access their values. i.e.,
public int getMainReg() {
return mainReg;
}
public int getCompareReg(){
return compareReg;
}
public Mode getCountMode() {
return countMode;
}
And make your fields all private. Also your code should obey Java naming rules: variable names should begin with lower-case letters.
Also be sure that you've initialized your counter variable in the class that uses it, either by creating a new instance, or if appropriate, passing in a valid instance in a constructor or method parameter.
The java.util.Observer and java.util.Observable are ugly. They require the sorts of casts that make type-safety fans uncomfortable, and you can't define a class to be an Observer of multiple things without ugly casts. In fact, in "How do I know the generic object that the Observer class sends in Java?", an answerer says that only one type of data should be used in each observer / observable.
I'm trying to make a generic version of the observer pattern in Java to get round both these problems. It's not unlike the one in the previously mentioned post, but that question was not obviously resolved (the last comment is an unanswered question from the OP).
Observer.java
package util;
public interface Observer<ObservedType> {
public void update(Observable<ObservedType> object, ObservedType data);
}
Observable.java
package util;
import java.util.LinkedList;
import java.util.List;
public class Observable<ObservedType> {
private List<Observer<ObservedType>> _observers =
new LinkedList<Observer<ObservedType>>();
public void addObserver(Observer<ObservedType> obs) {
if (obs == null) {
throw new IllegalArgumentException("Tried
to add a null observer");
}
if (_observers.contains(obs)) {
return;
}
_observers.add(obs);
}
public void notifyObservers(ObservedType data) {
for (Observer<ObservedType> obs : _observers) {
obs.update(this, data);
}
}
}
Hopefully this will be useful to someone.
I prefer using an annotation so a listener can listen to different types of events.
public class BrokerTestMain {
public static void main(String... args) {
Broker broker = new Broker();
broker.add(new Component());
broker.publish("Hello");
broker.publish(new Date());
broker.publish(3.1415);
}
}
class Component {
#Subscription
public void onString(String s) {
System.out.println("String - " + s);
}
#Subscription
public void onDate(Date d) {
System.out.println("Date - " + d);
}
#Subscription
public void onDouble(Double d) {
System.out.println("Double - " + d);
}
}
prints
String - Hello
Date - Tue Nov 13 15:01:09 GMT 2012
Double - 3.1415
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface Subscription {
}
public class Broker {
private final Map<Class, List<SubscriberInfo>> map = new LinkedHashMap<Class, List<SubscriberInfo>>();
public void add(Object o) {
for (Method method : o.getClass().getMethods()) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (method.getAnnotation(Subscription.class) == null || parameterTypes.length != 1) continue;
Class subscribeTo = parameterTypes[0];
List<SubscriberInfo> subscriberInfos = map.get(subscribeTo);
if (subscriberInfos == null)
map.put(subscribeTo, subscriberInfos = new ArrayList<SubscriberInfo>());
subscriberInfos.add(new SubscriberInfo(method, o));
}
}
public void remove(Object o) {
for (List<SubscriberInfo> subscriberInfos : map.values()) {
for (int i = subscriberInfos.size() - 1; i >= 0; i--)
if (subscriberInfos.get(i).object == o)
subscriberInfos.remove(i);
}
}
public int publish(Object o) {
List<SubscriberInfo> subscriberInfos = map.get(o.getClass());
if (subscriberInfos == null) return 0;
int count = 0;
for (SubscriberInfo subscriberInfo : subscriberInfos) {
subscriberInfo.invoke(o);
count++;
}
return count;
}
static class SubscriberInfo {
final Method method;
final Object object;
SubscriberInfo(Method method, Object object) {
this.method = method;
this.object = object;
}
void invoke(Object o) {
try {
method.invoke(object, o);
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
}
A modern update: ReactiveX is a very nice API for asynchronous programming based on the Observer pattern, and it's fully generic. If you're using Observer/Observable to "stream" data or events from one place in your code to another, you should definitely look into it.
It's based on functional programming, so it looks very sleek with Java 8's lambda syntax:
Observable.from(Arrays.asList(1, 2, 3, 4, 5))
.reduce((x, y) -> x + y)
.map((v) -> "DecoratedValue: " + v)
.subscribe(System.out::println);
I once wrote a generic implementation of the observer pattern for Java using dynamic proxies. Here's a sample of how it could be used:
Gru gru = new Gru();
Minion fred = new Minion();
fred.addObserver(gru);
fred.moo();
public interface IMinionListener
{
public void laughing(Minion minion);
}
public class Minion extends AbstractObservable<IMinionListener>
{
public void moo()
{
getEventDispatcher().laughing(this);
}
}
public class Gru implements IMinionListener
{
public void punch(Minion minion) { ... }
public void laughing(Minion minion)
{
punch(minion);
}
}
The full source code of AbstractObservable is available on pastebin. Way back I blogged about how it works in a bit more detail, also referring to related projects.
Jaana wrote an interesting summary of different approaches, also contrasting the dynamic proxy approach with others. Much thanks of course goes to Allain Lalonde from which I got the original idea. I still haven't checked out PerfectJPattern, but it might just contain a stable implementation of the observer pattern; at least it seems like a mature library.
Try to use class EventBus of Guava.
You can declare a Observer like this:
public class EventObserver {
#Subscribe
public void onMessage(Message message) {
...
}
}
New a EventBus like this:
EventBus eventBus = new EventBus();
And register Observer like this:
eventBus.register(new EventObserver());
Last notify Observer like:
eventBus.post(message);
I found a similar request but it was rather on codereview.
I think it's worth mentioning it here.
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Supplier;
/**
* like java.util.Observable, But uses generics to avoid need for a cast.
*
* For any un-documented variable, parameter or method, see java.util.Observable
*/
public class Observable<T> {
public interface Observer<U> {
public void update(Observable<? extends U> observer, U arg);
}
private boolean changed = false;
private final Collection<Observer<? super T>> observers;
public Observable() {
this(ArrayList::new);
}
public Observable(Supplier<Collection<Observer<? super T>>> supplier) {
observers = supplier.get();
}
public void addObserver(final Observer<? super T> observer) {
synchronized (observers) {
if (!observers.contains(observer)) {
observers.add(observer);
}
}
}
public void removeObserver(final Observer<? super T> observer) {
synchronized (observers) {
observers.remove(observer);
}
}
public void clearObservers() {
synchronized (observers) {
this.observers.clear();
}
}
public void setChanged() {
synchronized (observers) {
this.changed = true;
}
}
public void clearChanged() {
synchronized (observers) {
this.changed = false;
}
}
public boolean hasChanged() {
synchronized (observers) {
return this.changed;
}
}
public int countObservers() {
synchronized (observers) {
return observers.size();
}
}
public void notifyObservers() {
notifyObservers(null);
}
public void notifyObservers(final T value) {
ArrayList<Observer<? super T>> toNotify = null;
synchronized(observers) {
if (!changed) {
return;
}
toNotify = new ArrayList<>(observers);
changed = false;
}
for (Observer<? super T> observer : toNotify) {
observer.update(this, value);
}
}
}
Original answer from codereview stackexchange
I'm a beginner in Java, I used PHP, C++ and Lua and never had this problem, I made two classes just for exercising's sake Facto and MyFacto, first one does find a factorial and the second one should find factorial not by adding, but by multiplying. Don't blame me for the stupid and pointless code, I am just testing and trying to get the hang of Java.
Main:
public class HelloWorld {
public static void main(String[] args) {
Facto fc = new Facto(5);
fc.calc();
System.out.println(fc.get());
MyFacto mfc = new MyFacto(5);
mfc.calc();
System.out.println(mfc.get());
}
}
Facto.java:
public class Facto {
private int i;
private int res;
public Facto(int i) {
this.i = i;
}
public void set(int i) {
this.i = i;
}
public int get() {
return this.res;
}
public void calc() {
this.res = this.run(this.i);
}
private int run(int x) {
int temp = 0;
if(x>0) {
temp = x + this.run(x-1);
}
return temp;
}
}
MyFacto.java:
public class MyFacto extends Facto {
public MyFacto(int i) {
super(i);
}
private int run(int x) {
int temp = 0;
if(x>0) {
temp = x * this.run(x-1);
}
return temp;
}
}
I thought the result should be 15 and 120, but I get 15 and 15. Why is that happening? Does it have something to do with calc() method not being overriden and it uses the run() method from the Facto class? How can I fix this or what is the right way to override something like this?
The reason you're running into issues is due to member access visibility.
In a nutshell:
public allows any Java class to see the field/function, so long as it can be reached.
<package>, or no apparent modifier, allows any Java object (but not subclasses) to see the field/function, as long as they're in the same directory, or package.
protected allows the declared class and all other subclasses to access that field/function, as well as any class in the same directory/package.
private allows only the declared class to access that field/function.
To expand on what #Makoto said, you're running into an issue because the calc() method of Facto does not have access to the run() method of MyFacto, so it's using it's own run() method. Changing them both to protected instead of private should do the trick.
Also, something you should probably learn to use is the #Override annotation. It's good practice to put it above any method that you are overriding. That way, if you misspell something, or the parameters don't match, you will get a warning. Also, it makes it clear to you and/or the reader. For example:
MyFacto.java#run:
#Override
protected int run(int x) {
int temp = 0;
if(x>0) {
temp = x * this.run(x-1);
}
return temp;
}
Good luck with Java!
My code is basically allocation free, however the GC runs every 30 seconds or so when at 60fps. Checking the app with DDMS for allocation shows there is ALOT of SimpleListIterator being allocated. There is also some stuff being allocated because i use Exchanger.
The SimpleListIterator comes from for each loops for (T obj : objs) {}. I was under the impression that the compilator/translator would optimize those to not use iterators for types that support it (I basically only use ArrayList) but that seems to not be the case.
How can I avoid allocating all these SimpleListIterators? One solution would be to switch to regular for loops for (int i = 0; i < size; ++i) {} but I like for each loops :(
Another way would be to extend ArrayList which returns an Iterator that is only allocated once.
A third way I hacked together is using a static helper function which returns a Collection which is reusing an Iterator. I hacked something like this together but the casting feels very hackish and unsafe. It should be thread safe though as I use ThreadLocal? See below:
public class FastIterator {
private static ThreadLocal<Holder> holders = new ThreadLocal<Holder>();
public static <T> Iterable<T> get(ArrayList<T> list) {
Holder cont = holders.get();
if (cont == null) {
cont = new Holder();
cont.collection = new DummyCollection<T>();
cont.it = new Iterator<T>();
holders.set(cont);
}
Iterator<T> it = (Iterator<T>) cont.it;
DummyCollection<T> collection = (DummyCollection<T>) cont.collection;
it.setList(list);
collection.setIterator(it);
return collection;
}
private FastIterator() {}
private static class Holder {
public DummyCollection<?> collection;
public Iterator<?> it;
}
private static class DummyCollection<T> implements Iterable {
private Iterator<?> it;
#Override
public java.util.Iterator<T> iterator() {
return (java.util.Iterator<T>) it;
}
public void setIterator(Iterator<?> it) {
this.it = it;
}
}
private static class Iterator<T> implements java.util.Iterator<T> {
private ArrayList<T> list;
private int size;
private int i;
#Override
public boolean hasNext() {
return i < size;
}
#Override
public T next() {
return list.get(i++);
}
#Override
public void remove() {
}
public void setList(ArrayList<T> list) {
this.list = list;
size = list.size();
i = 0;
}
private Iterator() {}
}
}
You should not use for each in Android games.
I think this official video talks about that too.
Probably the best approach would be to use a Decorator design. Create a class which takes a collection in the constructor and implements the Iterable interface by calling the wrapped class and reusing the iterator returned.
Two additional approaches for avoiding the allocation of iterators.
First is to use a callback idiom:
public interface Handler<T> {
void handle(T element);
}
public interface Handleable<T> {
void handleAll(Handler<T> handler);
}
public class HandleableList<T> extends ArrayList<T> implements Handleable<T> {
public void handleAll(Handler<T> handler) {
for (int i = 0; i < size(); ++i) {
handler.handle(get(i));
}
}
}
This approach still requires an instance of a Handler to receive the callback, but this can definitely reduce allocations when, for example, you are trying to visit the elements of several lists.
Second approach is to use a cursor idiom:
public interface Cursor<T> {
void reset();
boolean next();
T current();
}
public class CursoredList<T> extends ArrayList<T> implements Cursor<T> {
private int _index = -1;
public void reset() {
_index = -1;
}
public boolean next() {
return ++_index >= size();
}
public T current() {
return get(_index);
}
}
Sure, this is the same as implementing Iterable and Iterator on your subtype of ArrayList, but this clearly shows the cursor location as state on the collection itself.