JAVA OBJECTS AND LINKS

This article discusses how to use the classes from the standard package 
java.lang.ref
, such as 
SoftReference
the WeakReference
PhantomReference
.

Consider an example where these classes may be needed. 

There is such task: it is necessary to realize the download from the server side to the client side of a client request.
To do this, you can implement a collection of objects on the client, which will be stored already loaded objects, so that when
the second request for the same object do not have to download it again, and give them in this collection, ie, implementation of the cache on the client.
Over time, the client will download a lot of new objects, save them to your collection, and previously downloaded items are already
no longer relevant, and just take up space in memory. Total - a mechanism cache-busting.

Here you can go different ways, look at some:

1. you can keep track of when the object is no longer used on the client, and then remove it from the collection.
However, this solution requires many changes in the logic of the client's operation, and is an ideal to other classes work with these objects transparently. 

2. To use the mechanism of "weak links" in Java.

What are these "weak links"?

In Java, references can be divided by "force."
The following are all four types of links sorted according to "force" (high to low):

1.  strong links (strong reference) . These are ordinary links that we always use. When we declare Rectangle rect = new Rectangle (), the object
referenced by the rect can not be removed by the garbage collector from the memory as long as the object has at least one strong link;

2.  soft links (SoftReference) . Ads soft links is as follows:

SoftReference rect = new SoftReference(new Rectangle());

You can use rect.get () method to obtain a Rectangle object itself. Get () method declared in class Reference, which are inherited from
SoftReference, WeakReference, PhantomReference. It is important to understand that the get () method can return null. This occurs when
your program memory is full, and there is the risk of an OutOfMemoryError, then the garbage collector removes objects that are referenced by
the soft link. It is this kind of links are useful for object caching.

3. The  weak links (WeakReference) .
The use of weak links is similar to using soft links, ad:

WeakReference rect = new WeakReference(new Rectangle());

The difference is that the object that is referenced by a weak link may be removed at any time by calling cborschika debris, ie
this does not necessarily low memory conditions.

4.  phantom links (PhantomReference) .
Creating a phantom reference is similar to the other:

PhantomReference rect = 

new PhantomReference(new Rectangle(), queue);

The difference is that there is necessarily classified the object
queue queue - is representative ReferenceQueue class. Queues are also used to SoftReference and WeakReference. Their function is
that when an object is accessible through a link is deleted, the object reference is available in ReferenceQueue queue. This
mechanism allows you to remove empty references.

Get () method is called in a phantom reference always returns null. This is
due to the fact what they are used.

Read more:   alignment in a table cell HTML CENTER

The fact that the weak link is put in place before the object to which it points will be
finalized (finalize ()) and deleted by the garbage collector. Those. the method finalize () object to be deleted may have a strict
reference to the deleted object, and thus to "save" it from the garbage collector. But the weak link will already be in the queue and will be destroyed.

Unlike phantom reference that it is placed in the queue only "into the" removal of the object to which it points - this is its main function.

Consider the weak links in a practical example.

Objects on that point, our links are class BigObject.

class BigObject {
  private int value;
  public BigObject(Integer pValue) {
    value = pValue;
  }
  @Override
  protected void finalize() throws Throwable {
    System.out.println("BigObject ("+value+") finalize()");
  }
  @Override
  public String toString() { return value+"";  }
}

The following objects are used for testing:

  List strongList; // сильные ссылки
        List> softList; // мягкие ссылки
        List> weakList; // слабые ссылки
        List> phantomList; // фантомные ссылки
        ReferenceQueue queue; // очередь
        List loadMemoryList; // здесь будут храниться ссылки на строки, которые
        // используются для загрузки памяти

To display the test results, we use the following methods:

private void printLists(){
  System.out.println("Strong references: ");
  for (BigObject bo : strongList) System.out.print(bo+" ");
  System.out.println();
  System.out.println("SoftReferences: ");
  printList(softList);
  System.out.println("WeakReferences: ");
  printList(weakList);    
  System.out.println("PhantomReferences: ");
  printList(phantomList);
}

private void printList(List> pList){
  for (Reference ref : pList)
    System.out.print(ref.get()+" ");

          System.out.println();
}

Methods of initialization and memory usage are as follows:

private void init(){
  strongList = new ArrayList();
  softList = new ArrayList>();
  weakList = new ArrayList>();
  phantomList = new ArrayList>();
  loadMemoryList = new ArrayList();
  queue = new ReferenceQueue();
  for (int i=0; i<3; i++){
    strongList.add(new BigObject(i));
    softList.add(new SoftReference(new BigObject(i)));

            weakList.add(new WeakReference(new BigObject(i)));
    phantomList.add(new PhantomReference(new BigObject(i), queue));
  }    
  printLists();
}

private void loadMemory(){
  for (int i=0; i<1200000; i++){
    loadMemoryList.add(i+"");
  }
}

Now we do the testing. For the first test we use the following code:

public void testPhantomReferences(){
  init(); // инициализация
  System.gc(); // вызов сборщика мусора
  System.out.println("garbage collector invoked");
  printLists(); // вывод
}

The result is:


        Strong references:
        0 1 2
        SoftReferences:
        0 1 2
        WeakReferences:
        0 1 2
        PhantomReferences:
        null null null
        garbage collector invoked
        Strong references:
        0 BigObject (2) finalize()
        BigObject (2) finalize()
        BigObject (1) finalize()
        BigObject (1) finalize()
        BigObject (0) finalize()
        BigObject (0) finalize()
        1 2
        SoftReferences:
        0 1 2
        WeakReferences:
        null null null
        PhantomReferences:
        null null null
    

Explanation: As previously mentioned, the phantom reference always returns null.
After calling the garbage collector have been deleted objects referred to by the reference phantom (PhantomReference) and weak links (WeakReference).
In the second test, consider the time of removing objects that are referenced by soft links (SoftReference). Test code is presented:


public void testSoftRefences(){
  init();
  System.gc();
  System.out.println("garbage collector invoked");
  printLists();
  System.out.println("memory usage increased");
  loadMemory(); // загрузка памяти
  System.out.println("loadMemoryList.size() = "+loadMemoryList.size());
  System.gc();
  System.out.println("garbage collector invoked");
  printLists();    
}

The result is:


        Strong references:
        0 1 2
        SoftReferences:
        0 1 2
        WeakReferences:
        0 1 2
        garbage collector invoked
        Strong references:
        BigObject (2) finalize()
        BigObject (1) finalize()
        BigObject (0) finalize()
        0 1 2
        SoftReferences:
        0 1 2
        WeakReferences:
        null null null
        memory usage increased
        loadMemoryList.size() = 1200000
        garbage collector invoked
        BigObject (2) finalize()
        BigObject (1) finalize()
        BigObject (0) finalize()
        Strong references:
        0 1 2
        SoftReferences:
        null null null
        WeakReferences:
        null null null
    

Explanation: In the first step the objects pointed to by weak links (WeakReference) were removed after calling the garbage collector.
Next there is a loading memory and recall the garbage collector. After that, deleted objects which
pointed soft links (SoftReference). As a result, after these actions were only objects with straight (strong) links to them.

Read more:   CREATE A NEW WEBSITE FOR TIMEWEB

findings

The use of different types of links in Java allows you to reduce the risk of memory leaks (memory leaks),
as well as increase the efficiency of memory usage. To implement the cache can be used WeakHashMap class.

Cherish the memory!

Ivan Kaplin, February 2010.

Additional Information

Plugging memory leaks with weak references:

http://www.ibm.com/developerworks/ru/library/j-jtp11225/index.html

Understanding Weak References:

http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html

Ссылки на api используемых классов:

http://java.sun.com/javase/6/docs/api/java/util/WeakHashMap.html

http://java.sun.com/javase/6/docs/api/java/lang/ref/Reference.html

http://java.sun.com/javase/6/docs/api/java/lang/ref/ReferenceQueue.html

http://java.sun.com/javase/6/docs/api/java/lang/ref/PhantomReference.html

http://java.sun.com/javase/6/docs/api/java/lang/ref/WeakReference.html

http://java.sun.com/javase/6/docs/api/java/lang/ref/SoftReference.html

Passing parameters to JAVA. - JAVARUSH

Variable in Java - a container, with a value in it. So what it means to "pass" variable? And what is the difference between primitive and reference data types.

We'll get to that later. Let's start with a simple assignment. What does this code:

int х = 3;
int у = х;


In line 1 creates a variable x of type int and it is assigned a value of 3.
At line 2, a variable y of type int and assign to it the value of the variable x .

In the future the variable x has no effect on y . Java copies the value of x (3) and places this copy in the near .

This transmission parameter meaningfully. You do not write one variable to another. Value is copied and assigned to the new variable.

The expression y = x; Does not mean "to write x to y ". It means "copy the value in x and write the copy from ".

If later I change y :

у = 34;

Will this affect the x ? Of course not. x has a value of 3 to continue.

If later I change x :

х = 90;

How will this affect y ? Nothing. They have nothing to do after the assignment (copying values) was done.

What about reference types? How do they work?

Not so difficult, in fact it is usually the same. Links do the same thing - you get a copy of the reference.

So, if I say:

Cat A = new Cat ();
Cat B = A;

Link A is copied to the link B . The facility is not true - you still just one object.
But now you have two different links that control the same object Cat .

Now let's consider the transfer of the parameters to the methods.

Java passes parameters by value. Is always.
This means - "copy the value and transmit a copy."

For primitive types, it's easy:

int х = 5;
doStuff (х); / / Передать копию х (значение 5) в метод doStuff

Method doStuff as follows:

Read more:   HOW TO KEEP GOOGLE MAPS OFFLINE

void DoStuff (int у) {

/ / Действия с 'y'
}

Copy value x , ie 5 is transmitted to the method doStuff () .

Method doStuff () has its own variable called y .
The variable y - the new, the other variable. A copy of what was in the x at the time of its transfer to the method. From this point on, in and x do not affect each other. When changing from , you do not affect x .


void doStuff (int у) {

у = 27; / / Это не влияет на 'х'
}

And vice versa - when you change x , you change y . The only thing that made the x in this case is to copy its value and gave it to the method doStuff () .

As "passing by value" works with links?

Too many people say, «Java passes primitives by value and objects of reference." It is not so as they say. Java passes everything by value. With a primitive, you get a copy of the contents. With links you also get a copy of the contents.

But what is the contents of references?

Remote control. Means to control / access to the object.

When you pass an object reference to a method, you are passing a copy of the reference. Remote control clone. The object is still sitting in a pile where he was created, waiting for someone to use the remote. The object does not care how many consoles "programmed" to control it. It is concerned only with the garbage collector, and you, the programmer.

Therefore, when you say:

Cat A = new Cat ();
doStuff (А);

void DoStuff (Cat B) {

/ / Использование B
}

There is only one object Cat . But now the two remote controls (links) can access the same object Cat .

So now all that B makes the object Cat , affect the Cat , pointed to A , but it will not affect the contents of A !

You can change the Cat , using the new link Bed and (copied directly from A ), but you can not change A .

What the hell does that mean?

You can change the object referenced by A , but you can not go and change the reference A - redirect it to another object or null . So if you change the link Bed and (not the object itself Cat referenced Bed and , and the value of links) you do not change the value of A . And vice versa.

So that:

Cat A = new Cat ();
doStuff (А);

void doStuff (Cat B) {

B = new Cat (); / / Не повлияет на ссылку A
}

It simply means that B points to another object. A still happy.

So repeat after me:

Java passes everything by value.

(Okay, one more time ... with feeling.)

Java passes everything by value.

For primitive types - you pass a copy of the current value for the object reference - you pass a copy of the reference (remote control). You will never pass an object. All objects are stored in a heap. Is always.

Now a hefty brew a cup of coffee and write code!

Original article.

Read in other languages

 BelorussianEnglish Deutsch Spanish French Italian Portuguese Turkish Arab Ukrainian Swedish Hungarian Bulgarian Estonian Chinese (Simplified) Vietnamese Romanian Thai Slovenian Slovak Serbian Malay Norwegian Latvian Lithuanian Korean Japanese Indonesian Hindi Hebrew Finnish Greek Dutch Czech Danish Croatian Chinese (Traditional) Philippine Urdu Azeybardzhansky ArmenianPolish Bengal Georgian Kazakh Catalan Mongolski Russian Tadzhitsky Tamilʹskij telugu Uzbetsky

Add a comment

Your e-mail will not be published. Required fields are marked *