Avatar billede horizon Nybegynder
04. maj 2010 - 22:34 Der er 12 kommentarer og
1 løsning

Bed et objekt om at begå selvmord

Har ikke rigtigt kunnet finde noget info omkring dette, så kaster lige spørgsmålet.

Er det muligt at bede et objekt om at slette sig selv i en anden metode i det samme objekt?

ie.:
class Foo{

  function sletObjekt(){
      //Udfør f.eks. db logik el. lign.
      //Slet dette objekt
  }

}

Jeg har prøvet med unset($this) og $this->__destruct(), men det giver mig intet resultat, og man kan ikke sige $this = null.

Er det en funktion der ikke er i php (endnu)?

Jeg ved godt man "bare" kan fjerne alle henvisninger til et objekt og så kalder garbage collectoren selv __destruct(), eller man kan benytte __unset(), men det virker som lidt dobbeltkonfekt at få objektet til at kalde handleren for at unsette et objekt hvis man lige så godt kan få objektet til at begå selvmord. Det kunne være i forbindelse med noget if/else kontrol i en metode el. lign.
Avatar billede arne_v Ekspert
04. maj 2010 - 22:38 #1
Hvorfor overhovedet blande dig i garbage collectorens arbejde?

Jeg er ikke PHP GC ekspert (jeg er ikke PHP anything ekspert), men i andre sprog er det fy fy at blande sig dens arbejde.
Avatar billede public2 Nybegynder
04. maj 2010 - 22:39 #2
Tror det du leder efter er unset()
Avatar billede public2 Nybegynder
04. maj 2010 - 22:40 #3
Arne_v, det er da ikke uset at bruge GC i Java?

Og jeg er ingen Java ekspert, så det skal opfattes som et nysgerrigt spørgsmål, fordi jeg kan huske at have lært om det og lært at bruge det ved flere lejligheder.
Avatar billede arne_v Ekspert
04. maj 2010 - 22:46 #4
I Java kan man godt lave kode som:

o = null;
System.gc();

men naar ens kode gaar i code review saa vil de andre udviklere finde baseball batsene frem og gennembanke en.

Tilsvarende i C# med:

o = null;
GC.Collect();
Avatar billede public2 Nybegynder
04. maj 2010 - 22:50 #5
Hehe, okay tak Arne.

Det skal jeg huske til mit eksamens projekt, vil så nødig gå til eksamen og ligne en voldforbryder (eller mangel på samme ;-))

Men hvorfor jeg spurgte var, at jeg netop brugte det i et projekt sidste år, hvor jeg simpelthen ikke kunne hitte en udvej uden at gøre det, et spørgsmål om en Dijkstra algoritme. Men jeg er ikke i tvivl om, at en mere habil Java udvikler ville have en bedre og mere optimal måde at løse problemet på :-)
Avatar billede horizon Nybegynder
04. maj 2010 - 22:53 #6
$arne_v
Ikke i java, der skal vi hjælpe GC så meget som muligt (det gavner i hvert fald i sidste ende).

Og jf. Information Expert design pattern('et?), så skal det objekt der indeholder de (fleste) informationer, varetage f.eks. sletningen af et objekt (f.eks. hvis du sletter noget fra en liste skal det tilsvarende slettes i databasen).

Og i bl.a. java er det 10 gange nemmere at udføre f.eks. sin sql og derefter kalde this.dispose i stedet for at fedte rundt efter de henvisninger der nu end måtte være, så slettes objektet og alle henvisninger bliver sat til null (så kommer der nullpointerexceptions, men det er jo så forventet i denne kontekst)

@public2
i php5 kan du ikke sige unset($this) jf. php.net/unset.
Avatar billede arne_v Ekspert
05. maj 2010 - 03:16 #7
I Java skal man hverken null'e eller kalde Systen.gc.

Og hvis du ikke tror paa mig, saa kan jeg godt give et par referancer.

Brian Goetz @ IBM Developerworks

http://www.ibm.com/developerworks/java/library/j-jtp01274.html


Helping the garbage collector . . . not

Because allocation and garbage collection at one time imposed significant performance costs on Java programs, many clever tricks were developed to reduce these costs, such as object pooling and nulling. Unfortunately, in many cases these techniques can do more harm than good to your program's performance.



Explicit nulling

Explicit nulling is simply the practice of setting reference objects to null when you are finished with them. The idea behind nulling is that it assists the garbage collector by making objects unreachable earlier. Or at least that's the theory.
...
Unfortunately, programmers often take this advice too far, using explicit nulling in the hope of helping the garbage collector. But in most cases, it doesn't help the garbage collector at all, and in some cases, it can actually hurt your program's performance.



Explicit garbage collection

A third category where developers often mistakenly think they are helping the garbage collector is the use of System.gc(), which triggers a garbage collection (actually, it merely suggests that this might be a good time for a garbage collection). Unfortunately, System.gc() triggers a full collection, which includes tracing all live objects in the heap and sweeping and compacting the old generation. This can be a lot of work. In general, it is better to let the system decide when it needs to collect the heap, and whether or not to do a full collection. Most of the time, a minor collection will do the job. Worse, calls to System.gc() are often deeply buried where developers may be unaware of their presence, and where they might get triggered far more often than necessary. If you are concerned that your application might have hidden calls to System.gc() buried in libraries, you can invoke the JVM with the -XX:+DisableExplicitGC option to prevent calls to System.gc() and triggering a garbage collection.


Effective Java / Joshua Bloch 1st Ed

Item 5


...
When programmers are first stung by a problem like this, they tend to overcompensate by nulling out every object as soon as the program is finished with it. This is neither necesarry nor desirable as it clutters up the program unnecesarrily and could conceivable reduce performance. Nulling out object referemces should be the exception rather than the norm.


Java Performance Tuning / Jack Shirazi

chapter 3


Prior to Java 2, explicit calls to System.gc() could assist an application. Garbage collection was pretty much an all-or-nothing affair and often you knew better than the garbage collector when it was a good time to start garbage collecting. But with the introduction of generational garbage collection, explicit calls to System.gc() become disruptive, possible forcing a full mark-sweep of th eheap when the generational garbage collector was doing just fine. So Sun has added an option to disable the effect of calling System.gc() explicitly: -XX:+DisableExplicitGC.


Og bemaerk at Java 2 (=J2SE 1.2) blev releaset i 1998.

Og her et eksempel fra den virkelige verden:

http://java-monitor.com/forum/showthread.php?t=188


As it turns out, the answer was really simple: the application was doing it to itself. An enterprising developer had decided to put in a call to System.gc(), the call in Java to suggest that the JVM do a garbage collect.

This call does not look so bad in itself. He'd placed it after pruning a large buffer, so he may have thought that that would be a good time to give the JVM a chance to take out the trash. What the developer did not realize was that System.gc() triggers a stop-the-world garbage collect cycle.

Now why is that so bad? It's only a few milliseconds overhead on each HTTP request, right? What harm can 100 ms do when there is lots of XML marshalling also going on? Well, the devil is in the fact that these 100 ms are not imposed on the current thread alone. Since you've just caused a stop-the-world garbage collect, all processing threads have to wait for 100 ms. What's worse, they all call System.gc() too. So each thread gets (number-of-threads * 100 ms) of GC overhead.

As if that was not enough: the number of threads that are in the process of handling an HTTP request grows larger and larger as requests are not processed quickly enough. More requests processing means more requests arriving and starting and calling System.gc(), thus causing yet more delays.
Avatar billede Slettet bruger
05. maj 2010 - 09:26 #8
Har også engang været NØDT til at garbage collecte "manuelt".
- i en servlet - modtog kæmpestore (50 MB) filer som BASE64, decodede og gemte på disk.

Garbage-collecteren gjorde faktisk sit arbejde, men var for længe om at komme igang.
Så i pressede perioder med mange "hits" åd servletten stille og roligt al memory i maskinen.

Det er muligt at det ikke var Kosher - men nødvendigt var det nu..
Avatar billede arne_v Ekspert
05. maj 2010 - 17:09 #9
Den spiser vel ikke mere memory end man har angivet med Xmx??
Avatar billede Slettet bruger
05. maj 2010 - 20:08 #10
Ja, ok. "maskinen" = servlet-engine'n (på en Lotus-Domino server)
- og objecterne den ikke ville slippe var notes
Så situationen var nok lidt speciel..
Avatar billede horizon Nybegynder
05. maj 2010 - 21:06 #11
Hmm... kunne godt være jeg lige skulle gribe fat i min lærer og høre lidt nærmere ang. GC'eren.

Smid et svar :)
Avatar billede arne_v Ekspert
06. maj 2010 - 01:19 #12
Bemærk at PHP er anderledes end Java. PHP er et helt andet runtime environment og helt andre GC metoder (jeg mener at PHP stadig bruger ref count).

Så der kunne godt være en forskel på hvad der er godt mellem PHP og Java. Men det første spørgsmål må være om der er en sådan forskel og ikke hvordan man gør hvis der er en forskel.

Bemærk at der godt kan være forskel på svaret alt efter hvordan PHP køres. Med CGI er GC ikke specielt relevant. Med mod_php kunne det godt være mere Java agtigt.

Lidt googling finder f.eks.:

http://www.tuxradar.com/practicalphp/18/1/10

som dog synes at være enig i Java/C# filosofien


Now, of course that is not quite true - unless you are really strapped for resources, there is little point calling unset() on each of your variables when you are done with them, and similarly there is little point in explicitly cleaning up after a resource just before the script is about to end, as it is going to happen anyway without the need to clog up your script.


http://bytes.com/topic/php/answers/638600-garbage-collection

ditto


This is what my boss likes to call "premature optimization." In
practice, you don't need to worry about any of this. If you run into
a specific problem, deal with it then. Un-setting all your variables
or setting them all to null when you're done will just clutter your
code. And yes, the memory used by a script should be released
automatically when the script is finished.
Avatar billede arne_v Ekspert
06. maj 2010 - 01:19 #13
og et svar
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Vi tilbyder markedets bedste kurser inden for webudvikling

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester