About Java references

2011-12-17 19:22

There is somewhat common misconception about garbage collecting, that it totally frees the programmer from memory-related concerns. Granted, it makes the task easier in great many cases, but it does so at the expense of significant loss of control over objects’ lifetime. Normally, they are kept around for at least until they are not needed anymore – and usually that’s fine for the typical definitions of “need” and “at least”. Usually – but not always.

For those less typical use cases, garbage-collected environments provide mechanisms allowing to regain some of that lost control, to the extent necessary for particular task. Java, for example, offers a variety of different types of references, enabling to change the notion of what it means for an object to be eligible for garbage collecting. Choosing the right one for a problem at hand can be crucial, especially if we are concerned with the memory footprint of our application. Since – as the proverb goes – JVM expands to fill all available memory, it’s good to know about techniques which help maintain our heap size in check.

The default is strong

So today, I will discuss the SoftReference and WeakReference classes, which can be both found in the java.lang.ref package. They provide the so-called soft and weak references, which are both considerably less powerful when it comes to prolonging the lifetime of an object.

Tags: , , ,
Author: Xion, posted under Programming » 1 comment

Decorators with Optional Arguments in Python

2011-12-13 18:34

It is common that features dubbed ‘syntactic sugar’ are often fostering novel approaches to programming problems. Python’s decorators are no different here, and this was a topic I touched upon before. Today I’d like to discuss few quirks which are, unfortunately, adding to their complexity in a way that often doesn’t feel necessary.

Let’s start with something easy. Pretend that we have a simple decorator named @trace, which logs every call of the function it is applied to:

  1. @trace
  2. def some_function(*args):
  3.     pass

An implementation of such decorator is relatively trivial, as it wraps the decorated function directly. One of the possible variants can be seen below:

  1. def trace(func):
  2.     def wrapped(*args, **kwargs):
  3.         logging.debug("Calling %s with args=%s, kwargs=%s",
  4.                       func.__name__, args, kwargs)
  5.         return func(*args, **kwargs)
  6.     return wrapped

That’s pretty cool for starters, but let’s say we want some calls to stand out in the logging output. Perhaps there are functions that we are more interested in than the rest. In other words, we’d like to adjust the priority of log messages that are generated by @trace:

  1. @trace(level=logging.INFO)
  2. def important_func():
  3.     pass

This seemingly small change is actually mandating massive conceptual leap in what our decorator really does. It becomes apparent when we de-sugar the @decorator syntax and look at the plumbing underneath:

  1. important_func = trace(level=logging.INFO)(important_func)

Introduction of parameters requires adding a new level of indirection, because it’s the return value of trace(level=logging.INFO) that does the actual decorating (i.e. transforming given function into another). This might not be obvious at first glance and admittedly, a notion of function that returns a function which takes some other function in order to output a final function might be – ahem – slightly confusing ;-)

But wait! There is just one more thing… When we added the level argument, we not necessarily wanted to lose the ability to invoke @trace without it. Yes, it is still possible – but the syntax is rather awkward:

  1. @trace()
  2. def some_function(*args):
  3.     pass

That’s expected – trace only returns the actual decorator now – but at least slightly annoying. Can we get our pretty syntax back while maintaining the added flexibility of specifying custom arguments? Better yet: can we make @trace, @trace() and @trace(level) all work at the same time?…

Looks like tough call, but fortunately the answer is positive. Before we delve into details, though, let’s step back and try to somewhat improve the way we are writing our decorators.

Tags: , , , ,
Author: Xion, posted under Programming » 2 comments

Synchronization Through Memcache

2011-12-10 18:11

In web and server-side development, a memcache is a remote service that keeps transient data in temporary, in-memory store and allows for fast access. It is usually based on keys which identify values being stored and retrieved. Due to storing technique – RAM rather than actual disks – it offers great speed (often less than few milliseconds per operation) while introducing a possibility for values to be evicted (deleted) if memcache runs out of space. Should that happen, oldest values are usually disposed of first.

This functionality makes memcache a good secondary storage that complements the usual persistent database, increasing the efficiency of the system as a whole. The usual scenario is to poll memcache first, and resort to querying the database only if the result cannot be found in cache. Once the query is made, its results are memcached for some reasonable amount time (usually called TTL: time to live), depending on allowed trade-offs between speed and being up-to-date with our results.

While making applications more responsive is the primary use case for memcache, it turns out that we can also utilize it for something completely different. That’s because memcache implementations offer something more besides the obvious get/set commands. They also have operations which make it possible to use memcache as synchronization facility.

Hello There!

2011-12-08 17:22

While saying ‘Hello!’ is entirely appropriate here, it is obviously not my first post on this blog. Not by a long shot: there are exactly 555 others that preceed this one, scattered across the timeframe of more than four years. They just happen to be written in slightly less widespread language and therefore reaching a significantly smaller audience. But even though technically I’m nowhere near a newbie when it comes to devblogging, I kinda feel like one now, after deciding to make a switch to English. Therefore it seems like a good idea to warmly greet everyone reading this.

So… hello there!

If it was truly an opening, I’d proceed to outline the purpose of this blog, explain what type of posts you can expect here and what subjects I’m planning to cover on (hopefully) regular basis. But although it is “just” a major checkpoint, it seems like a good idea to have this kind of introduction anyway. Not only for any newcomers that might have accidentally strolled around ;)

I called it a dev blog, and for good reason. Programming or coding or writing software – however you name it, that’s what I’m mostly going to cover here. More often than not, it will be related to my own experiences with diverse set of technologies, libraries, tools, frameworks and – most importantly – languages. The emphasis is intentional, because I’m quite a fan of programming languages in general: their semantics, unique features, the way they organize the structure of code written in them, and how they compare to each other. Therefore you can expect to see such topics being covered here; hopefully they won’t incite too much flames :)

Besides purely technical stuff, I will sometimes attempt to look at slightly bigger picture, going up to the “meta-level” of programming art. This includes any practice which aims to strengthen positive traits of one’s code: readability, flexibility, efficiency, etc. I might also ponder less explored (and usually more vague) topics, such as the cognitive process of turning ideas into algorithms, structures and actual code – but usually without going too far on the abstract side.

Of course I won’t entirely avoid posts that cannot be easily put into those two buckets. But even though they might be somewhat off-topic, I have a feeling they will be mostly related to IT anyway. What’s really interesting besides that, anyway? ;-)

Tags:
Author: Xion, posted under Computer Science & IT, Website » 5 comments

Zmiana językowa

2011-12-04 18:23

To nie była łatwa decyzja. Dość powiedzieć, że odwlekałem ją naprawdę bardzo długo. Nie bez związku był tu fakt, że wiąże się ona z nietrywialną ilością dodatkowych rzeczy do zrobienia – a przecież powszechnie wiadomo, że pracowitości raczej nie słynę :) Jestem jednak przekonany, że to już najwyższy czas.

Niniejszym informuję zatem, że oto oficjalnie zmieniam język, w którym piszę tego bloga. Kolejne notki będą już po angielsku. Być może nie absolutnie wszystkie, ale wszelkie wyjątki będą – właśnie tak – wyjątkami. Podobnie będzie też oczywiście z całą resztą interfejsu strony, którą to mam nadzieję stopniowo dostosować w ciągu najbliższych (tygo)dni.

Jeśli w swoich przewidywaniach nie mylę się koszmarnie, to krok ten nie powinien być dla większości czytających żadnym wielkim zaskoczeniem. Mógłbym tutaj rozpisać się na temat uniwersalności języka angielskiego wśród programistów, konieczności jego praktycznej znajomości, i tak dalej. Mógłbym, ale nie widzę w tym żadnego sensu – to są po prostu oczywistości, z którymi nawet nie ma jak polemizować. Dlatego mogę pewnie zaryzykować stwierdzenie, iż “wszyscy” wiedzieli, że i w przypadku tego bloga przejście na angielski jest wyłącznie kwestią czasu.

Istnieje oczywiście jeden główny powód tej zmiany, jakim jest możliwość znacznego poszerzenia grona odbiorców – żeby nie powiedzieć brzydko ‘grupy docelowej’ ;) Z tym zaś wiąże się też szereg pozytywnych konsekwencji, jak choćby o wiele większa swoboda w doborze tematów – zwłaszcza tych najbardziej interesujących, czyli stricte technicznych. Rozumowanie jest tu proste: w przepastnym oceanie światowego Internetu każda porcja praktycznej wiedzy znajdzie swojego odbiorcę. Gdy ograniczamy się do polskiej części sieci, nie jest to już takie pewne.

Drugą ważną przyczyną jest też to, iż pisanie po polsku na tematy okołokoderskie nie jest wcale łatwym kawałkiem chleba. Wymaga to bowiem ciągłego szukania kompromisów między precyzją opisu a jego długością, czytelnością, a często i językową poprawnością. Nierzadko trzeba tu też przecierać szlaki, próbując znaleźć zgrabne (i krótkie!) tłumaczenia dla rzadziej spotykanych pojęć technicznych. Nie w każdym przypadku jest to zresztą możliwe (“shader”?…) i wtedy pozostaje jedynie potraktować daną frazę kursywą. Ostatnio zresztą przytrafiało mi się to coraz częściej.

Ufam, że ta mała rewolucja zostanie przyjęta pozytywnie, albo chociaż z powściągliwym zrozumieniem :) Jednocześnie przepraszam z góry tych, przed którymi buduję właśnie językową barierę – mam nadzieję, że uda wam się szybko ją przekroczyć.

Do zobaczenia po drugiej stronie!

Tags: ,
Author: Xion, posted under Computer Science & IT, Website » 26 comments

W poszukiwaniu straconego czasu

2011-11-28 23:20

Kilka tygodni temu świat obiegła wiadomość o eksperymencie, wskazującym na możliwość istnienia neutrin poruszających się z szybkością większą niż świetlna. Rzeczone cząstki zostały wykryte o około 60 nanosekund wcześniej niż powinny, co wskazywałoby na to, iż właśnie o tyle szybciej przebyły nieco ponad 700-kilometrową odległość między szwajcarskim a włoskim laboratorium.

Czy owe 60 nanosekund to długo? No cóż, przychodzą tu do głowy dwie skrajne odpowiedzi. Z jednej strony to bardzo długo: w tym czasie fala elektromagnetyczna przebiegnie jakieś 60 metrów, a niedokładność tego rzędu byłaby kilkakrotnie większa niż zwyczajnego odbiornika GPS w nowoczesnym telefonie. Z drugiej strony jest to oczywiście niewyobrażalnie krótkie mgnienie oka – ale tylko w sensie metaforycznym, bo to rzeczywiste trwa przecież miliony razy dłużej.

Bardziej interesujące jest, jak taki odcinek czasowy ma się do przedziałów czasu, z którymi możemy mieć do czynienia podczas programowania. O ile rzędów wielkości różnią się od niego typowe interwały, z którymi stykamy się w różnego rodzaju aplikacjach?
Okazuje się, że o całkiem sporo… albo o bardzo niewiele. Na każdym z poziomów pośrednich dzieje się jednak zawsze coś ciekawego.

Tags: , , , ,
Author: Xion, posted under Computer Science & IT, Thoughts » 3 comments

Rozwiązywanie problemów w trzech prostych krokach

2011-11-23 23:59

Od początków istnienia Internetu, jedną z jego głównych funkcji było zadawanie pytań odpowiednio sprofilowanemu gronu słuchaczy – np. grupom dyskusyjnym Usenetu – i otrzymywanie na nie odpowiedzi. Narzędzia i sposoby komunikacji się zmieniają (mamy teraz fora, strony typu StackExchange, a nawet serwisy społecznościowe), ale ich przydatność w rozwiązywaniu programistycznych problemów pozostaje co najmniej niezmienna.

Odpowiednią pomoc możemy często znaleźć, przeszukując po prostu archiwum dyskusji. Niekiedy jednak musimy (lub chcemy) zadziałać aktywniej i założyć nowy wątek, opisując nasz problem. I tu podobno otwiera się przed nami całe uniwersum detali, o których powinniśmy pamiętać, i które zwykle zostały “wygodnie” zebrane do postaci kilometrowych poradników takich jak ten. Część z nich jest techniczna i często przestarzała (80 znaków w wierszu?…), a reszta nie jest dostatecznie poglądowa, aby uchwycić istotę sprawy.
A ta jest – według mnie – zupełnie nieskomplikowana i łatwa w praktycznym stosowaniu. Skuteczne prośby o pomoc w sprawach technicznych można bowiem rozważać jako proces obejmujący tylko trzy proste kroki – uniwersalne i niezależne od medium komunikacji.

Tags: , , ,
Author: Xion, posted under Computer Science & IT » 3 comments
 


© 2023 Karol Kuczmarski "Xion". Layout by Urszulka. Powered by WordPress with QuickLaTeX.com.