1)Reading the code of HashMap.java. In line 762, the annotation says subclass overrides this to alter the behavior of put method. However, the function void addEntry(int,K,V,int) is a private function. How can it be overrided by a subclass?
/**
758 * Adds a new entry with the specified key, value and hash code to
759 * the specified bucket. It is the responsibility of this
760 * method to resize the table if appropriate.
761 *
762 * Subclass overrides this to alter the behavior of put method.
763 */
764 void addEntry(int hash, K key, V value, int bucketIndex) {
765 Entry<K,V> e = table[bucketIndex];
766 table[bucketIndex] = new Entry<>(hash, key, value, e);
767 if (size++ >= threshold)
768 resize(2 * table.length);
2) In line 746 and 753, the two functions recordAccess and recordRemoval remain empty. So how can a subclass override these two functions?
static class Entry<K,V> implements Map.Entry<K,V> {
688 final K key;
689 V value;
690 Entry<K,V> next;
691 final int hash;
...
/**
742 * This method is invoked whenever the value in an entry is
743 * overwritten by an invocation of put(k,v) for a key k that's already
744 * in the HashMap.
745 */
746 void recordAccess(HashMap<K,V> m) {
747 }
748
749 /**
750 * This method is invoked whenever the entry is
751 * removed from the table.
752 */
753 void recordRemoval(HashMap<K,V> m) {
754 }
755 }
These methods are not private.
The accessibility when not specified is so called "package private". In particular, these methods can be overridden by other classes in the same package. The reason is probably that the Java authors want to be sure they can change/rename/replace this method anytime without breaking any application. When you are not sure that the API is good, it makes a lot of sense to keep those parts "package private", gather some experience with extending the class this way, and once you are sure the API is going to stay that way you can still make them public later on. However, you can't make them private, otherwise your own classes would also not be allowed to extend them!
To get a true private method, you should use the keyword private. Without any specification, the default is this so called "package private", and for public interfaces it even is public when nothing is specified.
If you are using eclipse, try Ctrl+T on the method name to see if any class overrides them.
Related
If vruntime is counted since creation of a process how come such a process even gets a processor if it is competing with a newly created processor-bound process which is younger let say by days?
As I've read the rule is simple: pick the leftmost leaf which is a process with the lowest runtime.
Thanks!
The kernel documentation for CFS kind of glosses over what would be the answer to your question, but mentions it briefly:
In practice, the virtual runtime of a task
is its actual runtime normalized to the total number of running tasks.
So, vruntime is actually normalized. But the documentation does not go into detail.
How is it actually done?
Normalization happens by means of a min_vruntime value. This min_vruntime value is recorded in the CFS runqueue (struct cfs_rq). The min_vruntime value is the smallest vruntime of all tasks in the rbtree. The value is also used to track all the work done by the cfs_rq.
You can observe an example of normalization being performed in CFS' enqueue_entity() code:
2998 static void
2999 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3000 {
3001 /*
3002 * Update the normalized vruntime before updating min_vruntime
3003 * through calling update_curr().
3004 */
3005 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
3006 se->vruntime += cfs_rq->min_vruntime;
3007
3008 /*
3009 * Update run-time statistics of the 'current'.
3010 */
3011 update_curr(cfs_rq);
...
3031 }
You can also observe in update_curr() how vruntime and min_vruntime are kept updated:
701 static void update_curr(struct cfs_rq *cfs_rq)
702 {
703 struct sched_entity *curr = cfs_rq->curr;
...
713
714 curr->exec_start = now;
...
719 curr->sum_exec_runtime += delta_exec;
...
722 curr->vruntime += calc_delta_fair(delta_exec, curr);
723 update_min_vruntime(cfs_rq);
...
733 account_cfs_rq_runtime(cfs_rq, delta_exec);
734 }
The actual update to min_vruntime happens in the aptly named update_min_vruntime() function:
457 static void update_min_vruntime(struct cfs_rq *cfs_rq)
458 {
459 u64 vruntime = cfs_rq->min_vruntime;
460
461 if (cfs_rq->curr)
462 vruntime = cfs_rq->curr->vruntime;
463
464 if (cfs_rq->rb_leftmost) {
465 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
466 struct sched_entity,
467 run_node);
468
469 if (!cfs_rq->curr)
470 vruntime = se->vruntime;
471 else
472 vruntime = min_vruntime(vruntime, se->vruntime);
473 }
474
475 /* ensure we never gain time by being placed backwards. */
476 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
...
481 }
By ensuring that min_vruntime is properly updated, it follows that normalization based on min_vruntime stays consistent. (You can see more examples of where normalization based on min_vruntime occurs by grepping for "normalize" or "min_vruntime" in fair.c.)
So in simple terms, all CFS tasks' vruntime values are normalized based on the current min_vruntime, which ensures that in your example, the newer task's vruntime will rapidly approach equilibrium with the older task's vruntime. (We know this because the documentation states that min_vruntime is monotonically increasing.)
It often happens to me when debugging or playing around in GHCi that I happen to know the actual ThreadId number (for example from using Debug.Trace), but that's all I have.
The problem is that all thread APIs, such as killThread require a ThreadId and not an Int.
I've tried Hoogle but came out empty. Is there a way to do this? I'm concerned mostly with debugging, so I don't mind if it's a nasty hack or if it's through a GHC-only library.
You can't. ThreadId is abstract. The Int you have is actually nothing more than a counter (source):
32 static StgThreadID next_thread_id = 1;
...
59 StgTSO *
60 createThread(Capability *cap, W_ size)
61 {
62 StgTSO *tso;
...
126 ACQUIRE_LOCK(&sched_mutex);
127 tso->id = next_thread_id++; // while we have the mutex
...
130 RELEASE_LOCK(&sched_mutex);
...
136 }
...
161 int
162 rts_getThreadId(StgPtr tso)
163 {
164 return ((StgTSO *)tso)->id;
165 }
It's rts_getThreadId that gets called in ThreadId's Show instance. There's no mapping back to the actual TSO. If you want to know what ThreadId belongs to what Int, you need to keep track of them yourself. You could, for example, parse the Int and fill a Map.
I'm trying to write code that gets a page and returns it PTE (page table entry) in the Linux kernel.
The prototype of the function should be something like this:
static pte_t getPteOfPage(struct page *page);
I tried to find the PTE of the page in the struct description of the page, but it is more complicated.
Can anyone show how to do it?
Good starting point to look at the walk_page_range function.
/**
143 * walk_page_range - walk a memory map's page tables with a callback
144 * #addr: starting address
145 * #end: ending address
146 * #walk: set of callbacks to invoke for each level of the tree
147 *
148 * Recursively walk the page table for the memory area in a VMA,
149 * calling supplied callbacks. Callbacks are called in-order (first
150 * PGD, first PUD, first PMD, first PTE, second PTE... second PMD,
151 * etc.). If lower-level callbacks are omitted, walking depth is reduced.
152 *
153 * Each callback receives an entry pointer and the start and end of the
154 * associated range, and a copy of the original mm_walk for access to
155 * the ->private or ->mm fields.
156 *
157 * Usually no locks are taken, but splitting transparent huge page may
158 * take page table lock. And the bottom level iterator will map PTE
159 * directories from highmem if necessary.
160 *
161 * If any callback returns a non-zero value, the walk is aborted and
162 * the return value is propagated back to the caller. Otherwise 0 is returned.
163 *
164 * walk->mm->mmap_sem must be held for at least read if walk->hugetlb_entry
165 * is !NULL.
166 */
See the walk_page_range function implementation, for a good example.
What is the best (idiomatic) way to concatenate Strings in Groovy?
Option 1:
calculateAccountNumber(bank, branch, checkDigit, account) {
bank + branch + checkDigit + account
}
Option 2:
calculateAccountNumber(bank, branch, checkDigit, account) {
"$bank$branch$checkDigit$account"
}
I've founded an interesting point about this topic in the old Groovy website: Things you can do but better leave undone.
As in Java, you can concatenate Strings with the "+" symbol. But Java
only needs that one of the two items of a "+" expression to be a
String, no matter if it's in the first place or in the last one. Java
will use the toString() method in the non-String object of your "+"
expression. But in Groovy, you just should be safe the first item of
your "+" expression implements the plus() method in the right way,
because Groovy will search and use it. In Groovy GDK, only the Number
and String/StringBuffer/Character classes have the plus() method
implemented to concatenate strings. To avoid surprises, always use
GStrings.
I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X} as I find it makes it more readable.
Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:
#Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*
def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
That gives me the following output on my machine:
Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
* JRE: 1.6.0_31
* Total Memory: 81.0625 MB
* Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64)
Options
=======
* Warm Up: Auto
* CPU Time Measurement: Off
String adder 539
GString template 245
Readable GString template 244
StringBuilder 318
StringBuffer 370
So with readability and speed in it's favour, I'd recommend templating ;-)
NB: If you add toString() to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder and StringBuffer beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion
Adding these tests (as it has been asked in the comments)
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
Now we get the results:
String adder 514
GString template 267
Readable GString template 269
GString template toString 478
Readable GString template toString 480
StringBuilder 321
StringBuffer 369
So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...
But still lots more readable.
Edit after comment by ruralcoder below
Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:
#Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )
def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer with Allocation' {
new StringBuffer( 512 ).append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
gives
Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
* JRE: 1.7.0_21
* Total Memory: 467.375 MB
* Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 630 0 630 647
GString template 29 0 29 31
Readable GString template 32 0 32 33
GString template toString 429 0 429 443
Readable GString template toString 428 1 429 441
StringBuilder 383 1 384 396
StringBuffer 395 1 396 409
StringBuffer with Allocation 277 0 277 286
def my_string = "some string"
println "here: " + my_string
Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.
Reproducing tim_yates answer on current hardware and adding leftShift() and concat() method to check the finding:
'String leftShift' {
foo << bar << baz
}
'String concat' {
foo.concat(bar)
.concat(baz)
.toString()
}
The outcome shows concat() to be the faster solution for a pure String, but if you can handle GString somewhere else, GString template is still ahead, while honorable mention should go to leftShift() (bitwise operator) and StringBuffer() with initial allocation:
Environment
===========
* Groovy: 2.4.8
* JVM: OpenJDK 64-Bit Server VM (25.191-b12, Oracle Corporation)
* JRE: 1.8.0_191
* Total Memory: 238 MB
* Maximum Memory: 3504 MB
* OS: Linux (4.19.13-300.fc29.x86_64, amd64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 453 7 460 469
String leftShift 287 2 289 295
String concat 169 1 170 173
GString template 24 0 24 24
Readable GString template 32 0 32 32
GString template toString 400 0 400 406
Readable GString template toString 412 0 412 419
StringBuilder 325 3 328 334
StringBuffer 390 1 391 398
StringBuffer with Allocation 259 1 260 265
I need a progress bar in my layout, which will have a total time of 30 secs and will tick every second. Basically I want the user of my app to see that he has 30 sec time before time is up.
This is the piece of code I have written.
But this gives me a blank progress bar with no activity. Please help.
What am I doing wrong
public class MySeekBarActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setProgressBarVisibility(true);
final ProgressBar progressHorizontal = (ProgressBar) findViewById(R.id.progress_horizontal);
progressHorizontal.setProgress(progressHorizontal.getProgress()* 100);
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
progressHorizontal.incrementProgressBy(1);
int dtotal = (int) ( 30000 - millisUntilFinished ) /30000 * 100;
progressHorizontal.setProgress(dtotal);
}
public void onFinish() {
// DO something when 2 minutes is up
}
}.start();
}
}
You've got a type conversion bug, due to two things:
you're dividing by an int, which causes the decimal to be rounded down,
also, you're casting the result too early, so even if you'd divide by a float/double, the result would get rounded down anyway.
To see what I mean - you can safely remove the cast to int from your code, and it will compile anyway. That means your final number is an int, and since you're not making any casts earlier, it means you're losing the decimal info pretty early on in the code.
This is a possible fix:
int dtotal = (int) (( 30000 - millisUntilFinished ) /(double)30000 * 100);
to resolve such bugs in the future, make a dummy Java program with a loop containing the equation, and print out the intermediate result, for example:
public class NumberTester {
//define the constants in your loop
static final int TOTAL_TIME = 30000;
static final int INTERVAL = 1000;
public static void main(String[] args) {
//perform the loop
for(int millisUntilFinished = TOTAL_TIME;millisUntilFinished >=0;millisUntilFinished -= INTERVAL) {
int dtotal = (int) (( TOTAL_TIME - millisUntilFinished ) /(double)TOTAL_TIME * 100);
System.out.println(dtotal);
}
}
}
Also, some important things:
don't start your timer in onCreate - your activity is not visible yet at this point! Use onResume instead.
kill your timer in onPause. Leaving timers and threads unmanaged like that is bad form, and may lead to weird bugs.
don't use "magic numbers". Place all your constant values in a static final class members, like I've done in the example. This will save you a lot of headaches when you decide to change those values.
EDIT: as to why your progress bar stops short of completion, that's because the onTick method works a bit differently than you're probably assuming it does. To see what I mean, add:
System.out.println("Milis:" + millisUntilFinished);
System.out.println("dtotal:" + dtotal);
to your onTick method. The values clearly don't count down to 0 (and hence 100 in the case of dtotal, it being derived from millisUntilFinished) - you have to compensate for that.