This sentence makes sense:
"James while John had had had had had had had had had had had a better effect on the teacher"
To better understand why, read it with added punctuation:
James, while John had had "had", had had "had had"; "had had" had had a better effect on the teacher.
Imagine a teacher giving a grammatical quiz, for which the answers 'had' and 'had had' were two potential responses.
If it helps to understand it, for the second and fifth 'had', substitute the word 'written'.