كيفية إزالة العناصر منتهية الصلاحية من HashMap وإضافة المزيد من العناصر في نفس الوقت - Java Timer و TimerTask والعقود الآجلة () - مثال كامل
نشرت: 2021-04-02
تعد Hashmap و ArrayList و Static Map و Vectors ، وما إلى ذلك من أكثر عناصر إطار عمل مجموعة Java استخدامًا. هناك عدد لا حصر له من السيناريوهات التي يمكنك استخدامها حسب حاجتك.
هذا المثال مثير للاهتمام Java مثال. سنقوم بتنفيذ العملية أدناه على HashMap واحد ().
- إنشاء كائن crunchifyMap
- استمر في إضافة عنصر إلى الخريطة كل ثانية والتي انتهت مدة صلاحيتها المحددة على
5 seconds
-
Check
من وجود عنصر منتهي الصلاحية مثل ذاكرة التخزين المؤقت كل ثانيةdelete from map if expired
- بعد 5 ثوانٍ ، ستحصل
always same size
always 5 elements
حيث تقوم بإضافة وحذف العناصر منتهية الصلاحية كل ثانية
أيضًا إذا كانت لديك below questions
، فأنت في المكان الصحيح:
- ما هو مثال خريطة منتهية الصلاحية الخاملة
- خريطة متزامنة مع عنصر مهلة
- مثال خريطة ذاكرة التخزين المؤقت لجافا
- Java TimerTask مثال
- Evictor - مثال على خريطة متزامنة جافا
هيا بنا نبدأ:
النقطة 1
- إنشاء عنصر مؤقت
crunchifyTimer
- يقوم بجدولة المهمة المحددة
CrunchifyReminder()
المتكرر ذي التأخير الثابت وهو ثانية واحدة - في مهمة مجدولة
-
add
عنصر إلى crunchifyMap - تحقق من العنصر منتهي الصلاحية من crunchifyMap وحذفه
-
النقطة 2
- أثناء عملية
addElement()
- نحن نربط
current time
لكل عنصر
- نحن نربط
- أثناء عملية
crunchifyClearExipredElementsFromMap()
- نحن نتحقق من الوقت الحالي مع وقت العنصر
- إذا كان فارق التوقيت أكثر من 5 ثوانٍ ، فما عليك سوى حذف العنصر من crunchifyMap
نقطة 3
- أثناء عملية إضافة وإزالة عنصر الطباعة على وحدة التحكم Eclipse
- سيتم إزالة العنصر المضاف الأول أولاً وهكذا
- يرجى التحقق من إخراج وحدة التحكم Eclipse للنتيجة
هنا برنامج Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
package crunchify . com . tutorials ; import java . util . ArrayList ; import java . util . Date ; import java . util . HashMap ; import java . util . Iterator ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Timer ; import java . util . TimerTask ; /** * @author Crunchify.com * <p> * - Keep adding element to Map every second which has expire time set to 5 seconds * - Check for expired element every second and delete from map if expired * - After 5 seconds you will get always same size as you are adding and deleting expired elements every second */ public class CrunchifyCleanExipredMapElements { Timer crunchifyTimer ; private static final long EXPIRED_TIME_IN_SEC = 5L ; private static final Map < Double , ArrayList < Date > > crunchifyMap = new HashMap < > ( ) ; public static void main ( String [ ] args ) { new CrunchifyCleanExipredMapElements ( 1 ) ; crunchifyLog ( "Start Adding element every second\n\n" ) ; } public CrunchifyCleanExipredMapElements ( int seconds ) { // Timer() - Creates a new timer. The associated thread does not run as a daemon. crunchifyTimer = new Timer ( ) ; // Schedules the specified task for repeated fixed-delay execution // schedule(): Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. // Subsequent executions take place at approximately regular intervals separated by the specified period. // In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. // If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. // In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate). crunchifyTimer . schedule ( new CrunchifyReminder ( ) , 0 , seconds * 1000L ) ; } // TimeTask: A task that can be scheduled for one-time or repeated execution by a Timer. // A timer task is not reusable. Once a task has been scheduled for execution on a Timer or cancelled, // subsequent attempts to schedule it for execution will throw IllegalStateException. class CrunchifyReminder extends TimerTask { public void run ( ) { // We are checking for expired element from map every second crunchifyClearExpiredElementsFromMap ( ) ; // We are adding element every second addElement ( ) ; } } public void addElement ( ) { crunchifyAddElementToMap ( Math . random ( ) ) ; } // Check for element's expired time. If element is > 5 seconds old then remove it private static void crunchifyClearExpiredElementsFromMap ( ) { // Date() - Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. Date currentTime = new Date ( ) ; Date actualExpiredTime = new Date ( ) ; // if element time stamp and current time stamp difference is 5 second then delete element actualExpiredTime . setTime ( currentTime . getTime ( ) - EXPIRED_TIME_IN_SEC * 1000L ) ; // size() - Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE. System . out . println ( "crunchifyMap size:" + CrunchifyCleanExipredMapElements . crunchifyMap . size ( ) ) ; Iterator < Entry < Double , ArrayList < Date > > > crunchifyIterator = CrunchifyCleanExipredMapElements . crunchifyMap . entrySet ( ) . iterator ( ) ; // hasNext() - Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.) while ( crunchifyIterator . hasNext ( ) ) { // next() - Returns the next element in the iteration. Entry < Double , ArrayList < Date > > entry = crunchifyIterator . next ( ) ; // getValue() - Returns the value corresponding to this entry. // If the mapping has been removed from the backing map (by the iterator's remove operation), the results of this call are undefined. ArrayList < Date > crunchifyElement = entry . getValue ( ) ; while ( crunchifyElement . size ( ) > 0 && crunchifyElement.get(0).compareTo(actualExpiredTime) < 0) { crunchifyLog("----------- Expired Element Deleted: " + entry.getKey()); crunchifyElement . remove ( 0 ) ; } if ( crunchifyElement . size ( ) == 0 ) { // remove() - Removes from the underlying collection the last element returned by this iterator (optional operation). // This method can be called only once per call to next. crunchifyIterator . remove ( ) ; } } } // Adding new element to map with current timestamp private static void crunchifyAddElementToMap ( Double digit ) { ArrayList < Date > crunchifyList = new ArrayList < > ( ) ; CrunchifyCleanExipredMapElements . crunchifyMap . put ( digit , crunchifyList ) ; // add() - Appends the specified element to the end of this list. crunchifyList . add ( new Date ( ) ) ; crunchifyLog ( "+++++++++++ Add Element:" + digit + "\n" ) ; } private static void crunchifyLog ( String string ) { System . out . println ( string ) ; } } |
إخراج وحدة التحكم Eclipse:
فقط قم بتشغيل البرنامج أعلاه وسترى النتيجة على النحو التالي.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
Start Adding element every second crunchifyMap size : 0 +++++++++++ Add Element : 0.6970683199424504 crunchifyMap size : 1 +++++++++++ Add Element : 0.8103548990859972 crunchifyMap size : 2 +++++++++++ Add Element : 0.849973176897403 crunchifyMap size : 3 +++++++++++ Add Element : 0.2770459184269851 crunchifyMap size : 4 +++++++++++ Add Element : 0.9136028332849369 crunchifyMap size : 5 ----------- Expired Element Deleted : 0.6970683199424504 +++++++++++ Add Element : 0.6630362698520832 crunchifyMap size : 5 ----------- Expired Element Deleted : 0.8103548990859972 +++++++++++ Add Element : 0.38906826918659854 crunchifyMap size : 5 ----------- Expired Element Deleted : 0.849973176897403 +++++++++++ Add Element : 0.3997935729434138 crunchifyMap size : 5 ----------- Expired Element Deleted : 0.2770459184269851 +++++++++++ Add Element : 0.20373441843273887 Process finished with exit code 130 ( interrupted by signal 2 : SIGINT ) |
اسمحوا لي أن أعرف إذا كنت تواجه أي مشكلة تعمل فوق برنامج Java.