Coding Gems – Gem #2 – Simple Scheduling

•January 14, 2012 • Leave a Comment

This has been there for a while but I find more people not knowing it exists than those who do. When thinking about scheduling in java most people think Quartz immediately.

Quartz is an amazing library indeed that I find my self bringing to almost every other application that I work on due to its ability to bring cron awesomness to my app mainly and because the idea of the job store is just so darn good when you get used to it. Most of what these people require however are much more simpler and is not really worth the overhead of bringing another dependency in, most people simply need to execute some logic every X units of time; and usually when they bring Quartz and after a while this scheduled logic starts taking more time than the interval between job triggers, they start realizing the fact that quartz will fire another instance of the job and you will be having multiple instances executing the same logic at the same time. So they scour the usual information sources and arrive at the conclusion that they need to have their logic in a StatefulJob.

Well if this all what you need you could use a hidden gem first introduced in 1.5, please all join me in welcoming today’s guest of honor the esteemed

java.util.concurrent

The package includes in its own package description words “Utility classes commonly useful in concurrent programming”. I will only be addressing the scenario described above.

  1. Grab a scheduled thread pool executer. The easiest way to do this is:
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    Please adjust the size of the pool according to the number of jobs you need, if you have a single scheduled job then a single thread is sufficient, add jobs more than the number of pooled threads will have them wait till another thread is available for execution.

  2. Implement your logic in the form of a runnable
    Runnable

    , you should account for the following while doing so:

    • If the job fails with an exception it will be suppressed by the scheduler, i.e. it will not trigger again until you reschedule it, whether you like this behavior or not (just prefer to swallow whatever exception the job might throw, log it and keep the schedule running) MAKE SOME NOISE WHEN YOUR JOB FAILS, send an email, write in a special log, show it on a dashboard… etc
    • If you have some external dependency that might block your logic, notice that no further executions will occur if you get trapped in one since we are emulating a stateful job, always set timeout parameters on external connections if you will use any, and again make as much noise as you can if you get to seem them in use.
  3. finally to emulate a StatefulJob just invoke:
    scheduler.scheduleWithFixedDelay([your-runnable-here], [initial-delay], [delay-between-executions], [time-unit-of-delay-parameters]);

For example if we invoke the method with the params 2,1,TimeUnit.MINUTES
We get our first execution after 2 minutes of the call with a single minute delay between each following execution, the delay is measured after the termination of a previous execution.
Assuming your job executes in 5 minutes we get the executions at:
2, 8, 14, 20, …
(initialDelay + (delay+job_duration)*n) where n = 0,1,2, ..

حبيبتي والمطر

•October 11, 2011 • Leave a Comment

أخافُ أن تُمطرَ الدُنيا، ولستِ معي
فمنذُ رُحْتِ … وعِندي عُقدةُ المَطَرِ

كانَ الشّتاءُ يُغَطِّيني بمعطفهِ
فلا أفكِّرُ في بردٍ ولا ضَجَرِ

وكانتِ الريحُ تعوي خلفَ نافذتي
فتهمسينَ: ” تَمَسَّكْ.. ها هُنا شَعري…”

والآنَ أجلسُ والأمطارُ تجلدُني
على ذراعي. على وجهي. على ظَهري

فَمَنْ يُدافِعُ عَنّي .. يا مُسافِرةً
مثلَ اليمامةِ، بينَ العينِ والبَصَرِ؟

وكيفَ أمحوكِ مِن أوراقِ ذاكِرتي؟
وأنتِ في القلبِ مثلُ النقشِ في الحجرِ

أنا أحِبُّكِ .. يا مَنْ تسكُنينَ دَمي
إنْ كُنتِ في الصّينِ أو إنْ كُنتِ في القَمَرِ

ففيكِ شيءٌ مِنَ المجهولِ أدخُلُهُ
و فيكِ شيءٌ مِنَ التّاريخِ والقَدَرِ

نزار قباني

•September 6, 2011 • Leave a Comment

QR download

My first android game :) Have a couple of blog posts drafted for this! for now! if you have android :) download and enjoy!

P.S. I know someone who is stealing interview questions off it so its not just a game :P

•September 6, 2011 • Leave a Comment

قمر تكامل في نهاية حسنه *** مثل القضيب على رشاقة قده

فالبدر يطلع من ضياء جبينه *** والشمس تغرب في شقائق خده

ملك الجمال بأسره فكأنما *** حسن البرية كلها من عنده

يا من حوى ورد الرياض بخده *** وحكى قضيب الخيزران بقده

دع عنك ذا السيف الذي جردته *** عيناك امضا من مضارب حده

كل السيوف قواطع ان جردت *** وحسام لحظك قاطع في غمده

ان شئت تقتلني فانت محكم *** من ذا يطالب سيد في عبده

أبو الطيب المتنبي

Coding Gems – Gem #1 – Java Sort Map by Value

•June 14, 2011 • 4 Comments
package com.wordpress.Oxcafebabe.gems;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * @author mahdeto
 *
 */
public class SortByValueMaps {

	public static void main(String[] args) {
		Map<String, Integer> test = new HashMap<String, Integer>(3);
		test.put("someValue", 1);
		test.put("aKeyThatNormallyComesBefore", 3);
		test.put("someOtherValue", 2);

		System.out.println(sortMapByValues(test));
	}

	public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValues(Map<K, V> sortMe) {
		List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(sortMe.size());

		entries.addAll(sortMe.entrySet());

		Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {

			@Override
			public int compare(Entry<K, V> o1, Entry<K, V> o2) {
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		Map<K, V> sortedMap = new LinkedHashMap<K, V>(sortMe.size());

		for(Map.Entry<K, V> entry : entries) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}

		return sortedMap;
	}

}

This outputs:
{someValue=1, someOtherValue=2, aKeyThatNormallyComesBefore=3}

زهور – أمل دنقل

•June 4, 2011 • Leave a Comment
وسلالٌ منَ الورِد,
ألمحُها بينَ إغفاءةٍ وإفاقه
وعلى كلِّ باقةٍ
اسمُ حامِلِها في بِطاقه
***
تَتَحدثُ لي الزَهراتُ الجميلهْ
أن أَعيُنَها اتَّسَعَتْ – دهشةً -
َلحظةَ القَطْف,
َلحظةَ القَصْف,
لحظة إعدامها في الخميلهْ!
تَتَحدثُ لي..
أَنها سَقَطتْ منْ على عرشِها في البسَاتين
ثم أَفَاقَتْ على عَرْضِها في زُجاجِ الدكاكينِ, أو بينَ أيدي المُنادين,
حتى اشترَتْها اليدُ المتَفضِّلةُ العابِرهْ
تَتَحدثُ لي..
كيف جاءتْ إليّ..
(وأحزانُها الملَكيةُ ترفع أعناقَها الخضْرَ)
كي تَتَمني ليَ العُمرَ!
وهي تجودُ بأنفاسِها الآخرهْ!!
***
كلُّ باقهْ..
بينَ إغماءة وإفاقهْ
تتنفسُ مِثلِىَ – بالكادِ – ثانيةً.. ثانيهْ
وعلى صدرِها حمَلتْ – راضيهْ…
اسمَ قاتِلها في بطاقهْ!

أناشيد الإثم و البراءة

•December 17, 2010 • 1 Comment

لو سألني أحدكم.. ما هي علامات الحب و ما شواهده لقلت بلا تردد أن يكون القرب من المحبوبة أشبه بالجلوس في التكييف في يوم شديد الحرارة و أشبه باستشعار الدفء في يوم بارد..

لقلت هي الألفة و رفع الكلفة و أن تجد نفسك في غير حاجة إلى الكذب.. و أن يرفع الحرج بينكما، فترى نفسك تتصرف على طبيعتك دون أن تحاول أن تكون شيئا آخر لتعجبها.. و أن تصمتا أنتما الإثنان فيحلو الصمت، و أن يتكلم أحدكما فيحلو الإصغاء..

و أن تكون الحياة معا هي مطلب كل منكما قبل النوم معا.. و ألا يطفئ الفراش هذه الأشواق و لا يورث الملل و لا الضجر و إنما يورث الراحة و المودة و الصداقة.. و أن تخلو العلاقة من التشنج و العصبية و العناد و الكبرياء الفارغ و الغيرة السخيفة و الشك الأحمق و الرغبة في التسلط، فكل هذه الأشياء من علامات الأنانية و حب النفس و ليست من علامات حب الآخر.. و أن تكون السكينة و الأمان و الطمأنينة هي الحالة النفسية كلما التقيتما.

و ألا يطول بينكما العتاب و لا يجد أحدكما حاجة إلى اعتذار الآخر عند الخطأ، و إنما تكون السماحة و العفو و حسن الفهم هي القاعدة.. و ألا تشبع أيكما قبلة أو عناق أو أي مزاولة جنسية و لا تعود لكما راحة إلا في الحياة معا و المسيرة معا و كفاح العمر معا

ذلك هو الحب حقا

و لو سألتم.. أهو موجود ذلك الحب.. و كيف نعثر عليه؟
لقلت نعم موجود و لكن نادر.. و هو ثمرة توفيق إلهي و ليس ثمرة اجتهاد شخصي
و هو نتيجة انسجام طبائع يكمل بعضها البعض الآخر و نفوس متآلفة متراحمة بالفطرة
و شرط حدوثه أن تكون النفوس خيرة أصلا جميلة أصلا
و الجمال النفسي و الخير هو المشكاة التي يخرج منها هذا الحب

و إذا لم تكن النفوس خيرة فإنها لا تستطيع أن تعطي فهي أصلا فقيرة مظلمة ليس عندها ما تعطيه

و لا يجتمع الحب والجريمة إلا في الأفلام العربية السخيفة المفتعلة.. و ما يسمونه الحب في تلك الأفلام هو في حقيقته شهوات و رغبات حيوانية و نفوس مجرمة تتستر بالحب لتصل إلى أغراضها

أما الحب فهو قرين السلام و الأمان و السكينة و هو ريح من الجنة، أما الذي نراه في الأفلام فهو نفث الجحيم

و إذا لم يكن هذا الحب قد صادفكم و إذا لم يصادفكم منه شيء في حياتكم فالسبب أنكم لستم خيرين أصلا

فالطيور على أشكالها تقع و المجرم يتداعى حوله المجرمون و الخير الفاضل يقع على شاكلته..

و عدل الله لا يتخلف .. فلا تلوموا النصيب و القدر و الحظ و إنما لوموا ..أنفسكم

د/ مصطفى محمود
أناشيد الإثم و البراءة

بقايا أمنية-فاروق جويدة

•November 8, 2010 • Leave a Comment

مازال في قلبي بقايا .. أمنية

أن نلتقي يوماً ويجمعنا .. الربيع

أن تنتهي أحزاننا

أن تجمع الأقدار يوماً شملنا

فأنا ببعدك أختنق

لم يبقى في عمري سوى

أشباح ذكرى تحترق

أيامي الحائرة تذوب مع الليالي المسرعة

وتضيع أحلامي على درب السنين الضائعة

بالرغم من هذا أحبك مثلما كنا .. وأكثر

مازال في قلبي…. بقايا أمنية

أن يجمع الأحباب درب

تاه منا .. من سنين

القلب يا دنياي كم يشقى

وكم يشقى الحنين

يا دربنا الخالي لعلك تذكر أشواقنا

في ضوء القمر

قد جفت الأزهار فيك

وتبعثرت فوق أكف القدر ..

عصفورنا الحيران مات .. من السهر

قد ضاق بالأحزان بعدك .. فانتحر

بالرغم من هذا

أحبك مثلما كنا .. وأكثر

في كل يوم تكبر الأشواق في أعماقنا..

في كل يوم ننسج الأحلام من أحزاننا..

يوماَ ستجمعنا الليالي مثلما كنا ..

فأعود أنشد للهوى ألحاني

وعلى جبينك تنتهي أحزاني..

ونعود نذكر أمسيات ماضية

وأقول في عينيك أعذب أغنية

قطع الزمان رنينها فتوقفت

وغدت بقايا أمنية

أواه يا قلبي ..

بقايا أمنية

 

Oldie But Goldy

•November 2, 2010 • 2 Comments

Abort, Retry, Ignore?

Once upon a midnight dreary, fingers cramped and vision bleary,
System manuals piled high and wasted paper on the floor,
Longing for the warmth of bed sheets, still I sat there doing spreadsheets.
Having reached the bottom line I took a floppy from the drawer,
I then invoked the SAVE command and waited for the disk to store,
Only this and nothing more.

Deep into the monitor peering, long I sat there wond’ring, fearing,
Doubting, while the disk kept churning, turning yet to churn some more.
But the silence was unbroken, and the stillness gave no token.
“Save!” I said, “You cursed mother! Save my data from before!”
One thing did the phosphors answer, only this and nothing more,
Just, “Abort, Retry, Ignore?”

Was this some occult illusion, some maniacal intrusion?
These were choices undesired, ones I’d never faced before.
Carefully I weighed the choices as the disk made impish noises.
The cursor flashed, insistent, waiting, baiting me to type some more.
Clearly I must press a key, choosing one and nothing more,
From “Abort, Retry, Ignore?”

With fingers pale and trembling, slowly toward the keyboard bending,
Longing for a happy ending, hoping all would be restored,
Praying for some guarantee, timidly, I pressed a key.
But on the screen there still persisted words appearing as before.
Ghastly grim they blinked and taunted, haunted, as my patience wore,
Saying “Abort, Retry, Ignore?”

I tried to catch the chips off guard, and pressed again, but twice as hard.
I pleaded with the cursed machine: I begged and cried and then I swore.
Now in mighty desperation, trying random combinations,
Still there came the incantation, just as senseless as before.
Cursor blinking, angrily winking, blinking nonsense as before.
Reading, “Abort, Retry, Ignore?”

There I sat, distraught, exhausted, by my own machine accosted.
Getting up I turned away and paced across the office floor.
And then I saw a dreadful sight: a lightning bolt cut through the night.
A gasp of horror overtook me, shook me to my very core.
The lightning zapped my previous data, lost and gone forevermore.
Not even, “Abort, Retry, Ignore?”

To this day I do not know the place to which lost data go.
What demonic nether world us wrought where lost data will be stored,
Beyond the reach of mortal souls, beyond the ether, into black holes?
But sure as there’s C, Pascal, Lotus, Ashton-Tate and more,
You will one day be left to wander, lost on some Plutonian shore,
Pleading, “Abort, Retry, Ignore?”

•August 28, 2010 • Leave a Comment

أنا لا أفكر..

أن أقاوم ، أو أثور على هواك..

فأنا وكل قصائدي..

من بعض ما صنعت يداك..

إن الغرابة كلها..

أني محاطٌ بالنساء..

ولا أرى أحداً سواك

–Nizar

 
Follow

Get every new post delivered to your Inbox.